Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New elements added without correct default values. #19

Closed
YLlywelyn opened this issue Sep 11, 2019 · 2 comments
Closed

New elements added without correct default values. #19

YLlywelyn opened this issue Sep 11, 2019 · 2 comments

Comments

@YLlywelyn
Copy link

When creating a new object with the + button all the fields in the new object are set to the c# default for that type instead of their default values from the class constructor (ints + floats = 0, string = empty, bool = false).

I've tested by adding a field next to the list that is a singular object. This object is initialised correctly, but the objects in the list are not. How can I get this working correctly?

image

@cfoulston
Copy link
Owner

cfoulston commented Sep 13, 2019

Yes, this is a limitation of the Unity Editor. Values in lists are set to their defaults (AFAIK)
What you can do is listen to the onAdd event, and manually add an item to the list:

[CustomEditor(typeof(AudioManager))]
public class AudioManagerEditor : Editor {

	private ReorderableList list;

	void OnEnable() {

		list = new ReorderableList(serializedObject.FindProperty("sounds"));
		list.onAddCallback += OnListAdd;
	}

	private void OnListAdd(ReorderableList list) {

		SerializedProperty property = list.AddItem();

		property.FindPropertyRelative("name").stringValue = "new sound";
		property.FindPropertyRelative("volume").floatValue = 1;
		property.FindPropertyRelative("pitch").floatValue = 1;
	}

	public override void OnInspectorGUI() {

		serializedObject.Update();

		list.DoLayoutList();

		serializedObject.ApplyModifiedProperties();
	}
}

If you remove the ReorderableList and just use default Unity array drawer. You should see the same issue occur. Default values not set. Unity has an issue for this: https://issuetracker.unity3d.com/issues/wrong-default-value-for-array-elements-added-in-inspector But I suspect it'll be postponed forever!

@YLlywelyn
Copy link
Author

Missed the callback, that'll fix it. Thanks for taking the time 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants