Combine values to give variable name?

So I don’t know if this can be done, certainly not how I am trying to do it, but there may be another way. Is it possible to combine two values when a script is running to produce a variable name already declared? So as an example:

var enemyShip1 : GameObject;
var enemyShip2 : GameObject;
var enemyShip3 : GameObject;
var enemyShip4 : GameObject;
var enemyShip5 : GameObject;
var enemyShip6 : GameObject;
var enemyShip7 : GameObject;
var enemyShip8 : GameObject;

var shipToSpawn : int = Random.Range (0,9);

function Start () {
var enemy1 = Instantiate (enemyShip+shipToSpawn, triggerPosition.position);
}

The idea being here that the number of the enemyShip that it returns is using the Random.Range at the end of the variable. Of course this returns an immediate error as Unity does not look at the combined value, so doesn’t know what ‘enemyShip’ is on its own. Is this possible in Unity?

No, use a collection like a list or array and have the number be the index in the array/list.

1 Like

Of course it is possible, however you would need to put the enemyShips into an Array or List<>.
This is the way to do it with an array.

var enemyShips : GameObject[9];

You populate that in the Inspector.

Then function Start() becomes:
var enemy1 = Instantiate(enemyShips[shipToSpawn], triggerPosition.position, quaternity.identity);

1 Like

Thanks for the swift replies. I’ll go with the array then. Interesting how it can merge variable names from an array but not two regular values.

It’s not merging a variable name. It’s accessing a value from a particular index in the array.

But it is combining two values (the random range variable and the array variable name) The value it accesses in the array is taken from a different variable outside the array.

Well yeah…you have to tell it which one you want…but it’s not combining or merging anything.