- Home /
TextAsset inside the Array - UnityScript/JavaScript
Hello i have a question regarding Arrays. Let's say i have a CSV file called weapons, i changed that CSV file into a TextAsset file and i would like to have an Array which will hold all my weapons from this TextAsset file and then in my function i will iterate through this Array to create a random number of items.
var weapons : TextAsset;
var itemsListArray : Array;
function InitialiseArray() {
itemsListArray = new Array ();
CreateRandomItemsFromArray();
}
private function CreateRandomItemsFromArray() {
var total : int = Mathf.Clamp(Random.value * 10, 4, 10);
for(var _cnt : int = 0; _cnt < total; _cnt++) {
var temp : int = Random.value * 24;
itemsListArray.Add(temp);
//Debug.Log(_cnt + " -- " + itemsListArray);
}
}
When i am passing weapons as a parameter in itemsListArray = new Array (); i am getting this error, but the items are being printed in Console.
InvalidCastException: Cannot cast from source type to destination type. Boo.Lang.Runtime.RuntimeServices.CheckNumericPromotion (System.Object value) Boo.Lang.Runtime.RuntimeServices.UnboxInt32 (System.Object value)
Also inside the window which is being opened to create random set of items. My first GUI Button is empty ad the rest of them are having integer values from CreateRandomItemsFromArray function
I changed my code and it's all working except i dont know how to store my newly created Random range of my items.
import System.Collections.Generic;
public var weaponsList : List.<TextAsset> = new List.<TextAsset>();
function InitialiseArray() {
weaponsList = new List.<TextAsset>();
CreateRandomItemsFromArray();
}
private function CreateRandomItemsFromArray() {
var total : int = $$anonymous$$athf.Clamp(Random.value * 10, 4, 10);
for(var _cnt : int = 0; _cnt < total; _cnt++) {
var temp : int = Random.Range(0,weaponsList.Count);
//weaponsList.Add(temp); //problem is here
Debug.Log(_cnt + " -- " + weaponsList);
}
}
my error message
The best overload for the method 'System.Collections.Generic.List..Add(UnityEngine.TextAsset)' is not compatible with the argument list '(int)'.
Answer by Eric5h5 · Mar 30, 2013 at 06:16 PM
Never use the Array class. Use a generic List, then you won't have those casting issues, plus it's much faster and better. Also you can just use Random.Range instead of using Random.value like that.