- Home /
Fill/populate [SerializeField] automatically via script in editor mode?
Is this possible? Let's say you have parent object with:
[SerializeField] List<Transform> children = new List<Transform>();
private void FillList()
{
foreach(Transform child in transform)
{
children.Add(child);
}
}
// AND TONS OF OTHER SCRIPTS + UPDATE()
Or even single [SerializeField] that you want to fill with GetComponent<>();
I want the SerializeField to be filled once and visible in the editor so I don't have to do it manually or at runtime. [ExecuteInEditMode]
comes to mind, but using it runs other unnecessary methods, I don't want to create separate script just for that
Answer by sisus_co · Sep 12, 2020 at 08:02 AM
If you only need to populate the list once when adding the component in edit mode, then you can simply use the Reset function.
void Reset()
{
FillList();
}
If you want a more robust solution, where the list is also repopulated every time the user changes any values of the component in the inspector, you can use the OnValidate function. This prevents the user from manually altering the contents of the list after the component has been added.
If you also need to react to changes made to the children, you can repopulate the list whenever the EditorApplication.hierarchyChanged event gets fired. This ensures that the list gets updated if some children are destroyed or new ones are added. You might need to use the ExecuteInEditMode attribute for this solution though, so that you can subscribe/unsubscribe to the event using the Start/OnDestroy events.
Answer by TelloSoft · Feb 17 at 09:49 AM
Hi, You can Auto Fill any Serialized Field by using this asset on the asset store.
contact for any query about the asset at autofill@tellosoft.com
Regards, Tellosoft
Answer by Lilliana69 · Feb 17 at 07:04 PM
When Unity serializes your scripts, it only serializes public fields. If you also want Unity to serialize your private fields you can add the SerializeField attribute to those fields.
Unity serializes all your script components, reloads the new assemblies, and recreates your script components from the serialized versions. This serialization is done with an internal Unity serialization system; not with .NET's serialization functionality.