- Home /
Inspector Doesn't Update Array Elements When Updated In Array Constructor
I am using an array to store unit class data for multiple unit types to allow easily edit-ability in the inspector. The idea is that I will easily be able to add more units as time goes on if desired by simply adding another new unit in the array's constructor.
--
The issue I am running in to is that whenever I add a new element in the array constructor the inspector does not update the array elements unless I reset the component, which wipes the set data back to defaults (something I do not want).
Here's sort of what I am doing just simplified:
public class Test : MonoBehaviour {
[SerializeField]
Unit[] allUnits = new Unit[]
{
new Unit("Fighter"),
new Unit("Brawler")
};
}
After saving the file and then adding it to a GameObject it will properly display the 2 Unit classes in the All Units array. Now, if I were to add another line, say new Unit("Tank")
, to the array constructor after placing the script on a GameObject and save the file the array on the GameObject will not be updated with the new Unit unless I Right-Click>Reset.
Am I missing something?
Answer by Glurth · Nov 28, 2017 at 08:50 PM
Those initial values are only applied when the Test component is created. Once it has been created, it uses the serialization system to save and load the values during instantiation . So, those initial values are set once, then saved and reloaded for THAT object's component. This is why you don't see "tank".
Notice that if you create ANOTHER gameobject now and add a NEW Test Component to it, you will find this one DOES include "tank".
Also note; if you were to exclude that [SerializeField] attribute, it would NOT serialize the field and NOT save/load the values, instead the initial values WOULD be applied every time the object is instantiated.