- Home /
Show Array Default Value in the Editor
Hi,
I have a simple object that has a Array that I want to contain one of each item in an enum by default.
How can I get the Array to show these default values in the Editor? for the most part they will not change but in a few cases (specifically while I'm testing the game) I want to change the values in the array in a few instances of the object.
Thanks for your help, Matt
Answer by Adam-Mechtley · Feb 22, 2017 at 08:46 AM
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using UnityEngine;
public enum MyEnum { FirstThing, SecondThing, ThirdThing }
public class NewBehaviourScript : MonoBehaviour {
static NewBehaviourScript()
{
List<MyEnum> defaults = new List<MyEnum>();
foreach (var v in Enum.GetValues(typeof(MyEnum)))
defaults.Add((MyEnum)v);
s_DefaultEnumValues = new ReadOnlyCollection<MyEnum>(defaults.ToArray());
}
static readonly ReadOnlyCollection<MyEnum> s_DefaultEnumValues;
[SerializeField]
List<MyEnum> m_EnumValues = s_DefaultEnumValues.ToList();
}
This is perfect, exactly what I was after. Thanks.
I think I understand how this works. But in the interest of me developing my c# skills could you explain why it works?
It seems that assigning the value in the constructor allows the array/list to be populated before it is shown in the editor? Why do we have to give the static ReadOnlyCollection values and then assign this to the List?
There are a couple of ways to assign a default value to a field on a $$anonymous$$onoBehaviour or ScriptableObject:
Using a field initializer (what I did here)
Assign a value in an instance constructor for the $$anonymous$$onoBehaviour/ScriptableObject (if you do this, you should make the constructor protected so no one using your code is tempted to try to call it directly)
Assign a value in the Reset() method for the $$anonymous$$onoBehaviour/ScriptableObject (this only gets called in the editor and would not happen if you e.g., add the component at run-time).
The reason I get the default values in the static constructor (not to be confused with an instance constructor in e.g., option 2 above) is because the values of this enum will never change, so i only want to obtain these default values one time, the first time this class is used. The reason I store them in a ReadOnlyCollection as opposed to e.g., a list or array is to prevent any unintended modifications to these default values at any later point from within the NewBehaviourScript class.
Awesome. Thanks for taking the time to explain that to me, really appreciate it!