- Home /
JS public array with starting values
Hello, I looked everywhere for an answer to this but I couldnt find any. I am trying to create a public array that starts with a few key/indexes. Doesnt pretty much matter which type. The thing is it doesnt save any of the values and it doesnt show in the inspector. The inspector either shows nothing or an array where I can define its size. So far I tried numerous approaches, including but not limited to: public var test : int[] = new Array(key: values); public var test: int[key:values]; public var test : int[4]; test[0] = 0... and so on. Is there a type to make a public array with a size and some values in it? or how is this done in unity? Many thanks!
Answer by robertbu · Feb 15, 2014 at 07:11 PM
The thing to know about public variables in JS is that any initialization is only executed when the script is attached. So changing code after the script is attached will not change the values in the Inspector. So take this script:
#pragma strict
var array : int[] = [1, 2, 3, 4];
function Start() {
Debug.Log(array.Length);
}
If you attach this to a game object in the inspector, you will see an array of four items with the values 1,2,3 and 4. But if later you then edit those items to say 2, 4, 6, and 8 in the script, the values will stay 1, 2, 3, and 4 when you examine the variables in the Inspector. In the Inspector, in the upper right of each component, there is a gear dropdown. You can select 'Reset' from this list and Unity will reinitialize all the variables as if the script was just attached. Note when you do this, you will lose any variables you initialzied by drag and drop to that component.
$$anonymous$$any thanks for your quick answer. However, my question was how can I create an array with some values that will also show in the inspector (not on play). For, if I create an array with var array : int[] = [1,2,3]
the inspector will show the variable array and it only says size 0. So not 4 fields with some values in it.
I know what you asked. This code will show the initialized array right after you attach it to a new game objct:
Create a new game object
Drag and drop the above script onto a game object
Look at the component in the Inspector
The 'Start()' is not necessary. It was just so that if you immediately run the app, you would see the values are initialized.
It must be something that i do wrong then. Because the only thing i see in the inspector is the array and when i press on it it says size 0. And also i would vote up your answer for your effort but i dont have enough reputation :((( my console logs the following: System.Int32[] UnityEngine.Debug:Log(Object) CubeController:Start() (at Assets/CubeController.js:10)
Ok, I'm so sorry for being so narrow $$anonymous$$ded. If i press on reset (As you said) it shows my values. Sorry again and many many thanks for your effort!