I’ve created an array of scripts all attached to the same game object and deactivated. What I’d like to do is to be able to pick three random members of the array and activate those scripts, drawing upon the variables within. However, I run into either a typing error at the outset (thus the untyped declaration here), or, when attempting to enable the script or access a variable, the error that either ‘enabled’ or ‘foo’ is not a member of ‘Object’. Is there a way to do this cleanly?
var myArray : Array = new Array();
function Start(){
myArray[0] = gameObject.GetComponent(Script0);
myArray[1] = gameObject.GetComponent(Script1);
myArray[2] = gameObject.GetComponent(Script2);
myArray[3] = gameObject.GetComponent(Script3);
myArray[4] = gameObject.GetComponent(Script4);
myArray[5] = gameObject.GetComponent(Script5);
myArray[1].enabled = true;
}
function Update (){
Debug.Log(myArray[1].foo);
}
Casting your random script instance to a MonoBehaviour may help as each script by default is a MonoBehaviour.
var script = myArray[1] as MonoBehaviour;
script.enabled = true;
Is ‘foo’ a member of all your scripts? You may need to create a base script and make all your scripts inherit from it. Then, cast to the base script type when you access ‘foo’.
If, according to comment, all the scripts have common variables, then create a BaseScript class derived from MonoBehaviour, with your variables. And then make all your scripts derive from this class.
Additionally, don’t use Array class. Use either strongly typed array or generic list. For above base class, this would be:
var myArray : BaseScript = new BaseScript[6]; // you have to declare size
or
var myList : List.<BaseScript> = new List.<BaseScript>(); // requires importing System.Collections.Generic namespace
If you use list, then you can add elements to it using