Skip to content

Instantly share code, notes, and snippets.

@hariedo
Last active December 23, 2025 19:38
Show Gist options
  • Select an option

  • Save hariedo/6b48e8a28827de6ca80cd4529b1fd03d to your computer and use it in GitHub Desktop.

Select an option

Save hariedo/6b48e8a28827de6ca80cd4529b1fd03d to your computer and use it in GitHub Desktop.
// 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