A question about instantiating.

I’ve got a game manager script in which I instantiate a prefab, call it “enemy”. Now this enemy has a script that sometimes needs to ask various questions of the game manager, and so the enemy script includes a reference to the game manager. As I see it, there are a few ways I could handle this, all of which seem to have shortcomings:

a) Use Find to set up this pointer to the game manager in enemy’s Start function, but this seems like overkill – after all, the game manager just built the enemy, so you’d think the game manager should be able to let the enemy know how to find it.

b) Immediately after the game manager instantiates the enemy, have the game manager set the enemy’s manager field. Here the problem is that it (sometimes) gives a run-time error, as the enemy may begin running before the game manager gets to set the enemy’s manager field.

c) Adjust b) by having the enemy wait some amount of time before doing anything. This seems pretty ugly, since who knows how much time it actually needs to wait.

d) Adjust b) by having a “ready” field that the manager sets to true only when it has done the necessary initialization, and do a ready check before running the contents of Update. Or equivalently, only run the contents of Update if the manager field isn’t null. But this check will now be run on every update, even though once it is true, it’ll be true forever.

Is there a better/cleaner way to handle this? Or is this indicative of a structural problem – maybe I should somehow set things up so enemy never needs access to the manager, and it is always the manager that talks to the enemy – but I don’t see how I’d do that either. Any suggestions? Thanks very much in advance.

If you use static variables and functions in the manager this shouldn’t be an issue.

//In the Enemy script
enemyVariable = GameManager.someVariable;
//or
enemyVariable = GameManager.SomeFunction(passSomeVariableIn, andYetAnother);

//In the Game Manager script
static var someVariable : boolean = true;
static function SomeFunction (someVariable : int, anotherVariable : int) : boolean {
    var returnThis : boolean = false;
    if (someVariable==anotherVariable) returnThis = true;
    return returnThis;
}

Although sometimes you need to keep a reference to a non-static part of a script, then you could make one static variable for a series of objects and reference to it with GetComponent. You could make the GameManager reference to itself for a non-static variable or function (GameManager.gmScript.thePublicVariable) where gmScript is declared: static var gmScript : GameManager;. Then set in Awake(): gmScript = GetComponent(GameManager);.

Another way of solving it is by having a static variable in the multiple objects and then finding the component once if it’s null, otherwise do nothing. This has next to none impact on initialization. Although, keeping a manager static is the easiest way to go.