Last active
December 23, 2025 19:38
-
-
Save hariedo/6b48e8a28827de6ca80cd4529b1fd03d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // UnityElementInitialization.cs | |
| // | |
| using System; | |
| using UnityEngine; | |
| // In Unity, new struct or class elements in a serialized list do not | |
| // get a chance to run static initializers or constructors. All members | |
| // are given their default(T) values instead. This is an example of how | |
| // to use the OnValidate() method to support initialization. | |
| public class MyBehaviour: MonoBehaviour | |
| { | |
| public List<Thingy> thingies = new(); | |
| [Serializable] | |
| public class Thingy | |
| { | |
| public string name; | |
| public float threshold; | |
| [HideInInspector] public bool __init = false; | |
| public void OnValidate() | |
| { | |
| // fix invalid values | |
| if (threshold < 0f) | |
| threshold = 0f; | |
| // defaults set once | |
| if (__init) return; __init = true; | |
| if (threshold == 0f) | |
| threshold = 0.5f; | |
| } | |
| } | |
| public void OnValidate() | |
| { | |
| if (thingies != null) | |
| foreach (var thingy in thingies) | |
| thingy?.OnValidate(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment