Setting variables in instances via GetComponent

Hi,

I’ve followed a number of posts regarding best practices with accessing script variables functions through GetComponent, and it all works great, except for one issue:

I have a Manager script which instantiates an object (an enemy) X times, and for each enemy instance it sets the GameObject properties for position, rotation, and a variable, “enemySpeed”

The transforms set fine for each instance, but always the last instance created resolves to a value of 0 for enemySpeed. If I only create one instance, enemySpeed resolves to zero.

If I set the variable via a function, and put a print(enemySpeed) function inside it, this returns the correct value (a random float), but then enemySpeed resolves itself back to zero (or if I put a value in the inspector, it will resolve to that).

Follow?

Here’s the code, condensed to just the problem::

Manager.js

var enemy : GameObject;
private var enemyInstance : GameObject;
private var enemyScript : EnemyScript;

function Start() {

for (var i = 0; i < 6 ; ++i)
{
    enemyInstance = GameObject.Instantiate(enemy);
    enemyScript = enemy.GetComponent(EnemyScript);
    print (enemyScript.setState(10.0));
}

EnemyScript.js

public var enemySpeed;

public function(sp)
{
enemySpeed = sp;
return enemySpeed;
}

function Update()
{
print enemySpeed;

In your code, you set the speed of the original object you instantiate instead of the instance you created. So the speed is set to the original and then reflected on the next object instantiated.
The object always uses the last value, which is presumably 0 at the beginning.

i.e. the line in the for loop should be:

That’s a booboo then!

I left that in when I was trying to figure out how GetComponent worked, totally blindsided myself there.

Thanks Adrian, seriously appreciated :slight_smile:

Got to say, Unity drove me nuts at first, it’s taking longer to learn than just switching between languages, but it’s proving itself to be up there ahead some of the best environments I’ve seen. Totally brilliant.