- Home /
public fixed size array in inspector
Is there a way to create a public fixed size array visible in the inspector? I want to do something like the Particle Animator's 'Color Animation' variable where it appears like this in the inspector:
ColorAnimation[0]
ColorAnimation[1]
ColorAnimation[2]
ColorAnimation[3]
ColorAnimation[4]
Answer by v01pe_ · Sep 13, 2015 at 09:43 PM
I recently did this by using OnValidate() to check for size modifications and resetting the size to what I want it to be, while keeping the array contents:
private const int SIZE = 5;
public int[] ints = new int[SIZE];
void OnValidate()
{
if (ints.Length != SIZE)
{
Debug.LogWarning("Don't change the 'ints' field's array size!");
Array.Resize(ref ints, SIZE);
}
}
Only downside is, that when you have a second variable referencing the same array for whatever reason (like private int[] myInts = ints
), the second variable still keeps the old array. But that's not something one usually does I guess.
And you even can set it to private if you set it to [SerializeField] ! Very nice
Answer by Molix · Feb 07, 2011 at 03:17 PM
I think you'd need to use a custom inspector. In DrawInspectorGUI, you'd have something like:
void OnInspectorGUI() { MyComponent myComp = target as MyComponent;
for( int i=0; i<5; ++i ) { myComp.ColorAnimation[i] = EditorGUILayout.ColorField( "ColorAnimation[" + i + "]",
myComp.ColorAnimation[i] ); } }
Answer by Berenger · Dec 20, 2010 at 10:38 AM
if you mean to rofbid possibility for users to change the size, I'd say use regular variables. But if you just want your array to appear in the inspector, you need built-in array :
var ColorAnimation : Color[] = new Color[5];
Then, in the inspector, you'll have :
ColorAnimation :
Size 5
Element 0 = Color
Element 1 = Color
Element 2 = Color
Element 3 = Color
Element 4 = Color
The problem is the array can be resized from the inspector which is not what I want.
how can we set the array size by using script? i mean i know we can set it manually in inspector but i am working on something and it's size must be changed by script, any one help me?
Answer by alisher8 · Apr 25 at 06:47 AM
Hey everyone i know this is a very old Q/A but can someone help me in how can we set the array size by using script? i mean i know we can set it manually in inspector but i am working on something and it's size must be changed by script, any one help me?
For an array, you need to redefine it:
For an int array: int array = new int[size];
However, I'd suggest using lists (more info here) since they can be resized dynamically!