Values added during editor mode are removed when starting playmode
I have nodes in my game, that have a List filled with connected nodes. I don't want to manually add nodes to each other with drag and drop, but I want to connect all nodes that are currently selected in the editor. I wrote this script:
[MenuItem("Node Tools/Connect Selected Nodes %g")]
static void ConnectSelectedNodes() {
List<AbstractNode> selectedNodes = new List<AbstractNode>();
foreach (GameObject n in Selection.gameObjects) {
if (n.GetComponent<AbstractNode>() != null) {
selectedNodes.Add(n.GetComponent<AbstractNode>());
}
}
Debug.Log(selectedNodes.Count);
foreach (AbstractNode n in selectedNodes) {
foreach (AbstractNode c in selectedNodes) {
if (n.gameObject != c.gameObject) {
Undo.RecordObject(n, "Added connection");
n.AddConnection(c);
}
}
}
}
The connection gets added in the inspector, but when I press play, every field in the array switches to "null" and stays like that after stopping the game.
I hope you guys can help me with this problem.
Answer by ElijahShadbolt · Nov 13, 2016 at 07:27 PM
It would be good to see your AbstractNode class.
When calling n.AddConnection(c)
, are you changing any private variables, say, adding the other node to a list? Any fields you change must have an attribute [SerializeField]
in front of it, or the changes won't be saved for runtime.
If AbstractNode is a struct or a class instead of a MonoBehaviour script, it might also need to have the attribute [System.Serializable]
. This makes the values appear in the Inspector, and I think it allows changes to be saved.
The list in AbstractNode is private, but uses [SerializeField] so I can still see it in the inspector. AbstractNode is also a $$anonymous$$onoBehaviour.
Hmm. I've made my own AbstractNode script, with a System.Collections.Generic.List and an AddConnection function, and it seems to be working fine for me. The list items don't get deleted on Play.
Sometimes certain types of classes and structs cannot be serialized by default with Unity, like Dictionaries. $$anonymous$$aybe you are using a different sort of data container, not just a list or array?
Answer by Thomas-Hawk · Nov 14, 2016 at 07:30 AM
Does the object in question come from a prefab with values of its own?
Your answer
Follow this Question
Related Questions
Editor Window script getting values from another script 1 Answer
Unity 4.1.5 is not showing certain public variables in the inspector 1 Answer
How can I edit InputField's Inspector? 0 Answers
Dynamically sized list of toggles in custom inspector? 0 Answers
Drawing a scene in the inspector GUI 0 Answers