In a custom inspector, I am adding a new custom class “DSReaction” element to a native array named “reactions” obtained via a SerializedProperty. To add the new element to the “reactions” array, I’m using the “InsertArrayElementAtIndex” function.
Here is a stripped-down version of the code:
using UnityEditor;
[CustomEditor(typeof(DSReacter))]
public class DSReacterEditor : Editor
{
private DSReacter T;
private SerializedObject Reactor;
private SerializedProperty reactions;
private void OnEnable()
{
T = target as DSReacter;
Reactor = new SerializedObject(T);
reactions = Reactor.FindProperty("reactions");
}
public override void OnInspectorGUI()
{
Reactor.UpdateIfDirtyOrScript();
if (GUILayout.Button("New Reaction"))
reactions.InsertArrayElementAtIndex(0);
Reactor.ApplyModifiedProperties();
}
}
Unfortunately, if the array is not empty, this automatically creates the new element using the variable valuables of the preceding element.
How can I add a new element, but have it retain the default class variable values, as opposed to the values of the preceding element?
Thank you in advance, and be well!
- S.
@Bunny83: Yes, you assumed correctly that T.reactions is a native array. I had presumed that I was overlooking a method offered by SerializedProperty. Glad to know that it was the lack of a method as opposed to my inability to locate one. Thank you for your response and example. I've tested it, and it works perfectly. Additionally, I've updated my original post to clarify it for future reads based on your comment. Thank you again, and be well! \- S.
– S_DarkwellWouldn't it be possible to do something like reactions.InsertArrayElementAtIndex(0); reactions.GetArrayElementAtIndex(0).objectReferenceValue = new Reaction(); instead?
– Plattinator