Setting instance variables...puzzled...

Hi,

I’ve followed a number of great 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 < 2 ; ++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);
}

This outputs 10,10 (which is right), then 10,0, 10,0, 10,0, 10,0…etc…

This can’t be a bug, as it has to be a fairly common operation, so what have I missed? Have I made an obvious booboo?

-pw

In the second line of your loop, you call enemy.GetComponent when you wanted enemyInstance.GetComponent. I bet this is the cause of your confusion. Though, I don’t see “setState” defined anywhere and I don’t know what it’s supposed to do so I can’t say for sure that’ll fix you problem.