- Home /
Array "size" question.
I have this variable
var scriptsNames: String[] = new String[0];
declared outside any function
now when I try to assign
function Start(){
scriptsNames[0] = "name1";
scriptsNames[1] = "name2";
scriptsNames[2] = "name3";
scriptsNames[3] = "name4";
}
Unity gives me errors. it can be fixed if I change, outside, in the Unity inspector http://img46.imageshack.us/img46/5198/gownon.png size, over here.
but I suppose it can be changed inside a script, somehow? Is anybody willing here to show me how to access it, and change it to 4, for example, using scripting?
Thank you in advance.
Answer by spinaljack · Sep 24, 2010 at 09:50 PM
http://unity3d.com/support/documentation/ScriptReference/Array.html
The difference between a Unity array and a java script array is that Unity arrays cannot be resized so unless you know the exact size of an array before run time you should stick with java script arrays.
To make one of those you type:
var array = new Array();
and then all the basic array functions can be carried out on it like push and pop.
To create a Unity array (which are faster) with a fixed size you type:
var unityArray: String[];
function Start(){ unityArray = new String[4]; }
You can switch between the two types using the array.ToBuiltin() function
P.S. It might not apply to you but I've noticed that creating large complex arrays may take more than one frame so trying to assign a value straight away sometimes leads to out of bounds errors (yes, sometimes..). To get around this I added an array check with a yield to wait for the array to finish initialising before assigning values to it.
Allright man, thanks for that. Your answer led me straight to what I needed. Thank you!
I seriously doubt it's possible for arrays to take more than one frame to create. If it's not an atomic operation, Unity would be pretty broken.
I had an error where exactly this was true, it was an array of classes though which also contained arrays
Also, the classes were just a method for storing different data types together, they don't have any functions.
Your answer
Follow this Question
Related Questions
Why is my Array going out of bounds?? 1 Answer
Find the average of 10 Vectors 4 Answers
JavaScript String Question 2 Answers
Instantiating random prefabs 1 Answer
Wrong object always Instantiated 1 Answer