yet another GetComponent q

UnityException: You are not allowed to call this function when declaring a variable

seems to be tied to this:

var zoneTarget : DoorZone = gameObject.GetComponent(DoorZone);

DoorZone is a GO that has another script attached I’m getting a variable from.

Firefox on my Mac reports Firefox-bin quit but continues to run the player without problem. Explorer on a WindowsXP machine with 815 graphics crashes. Could the above exception be causing it?

hmm… Just realized my game object and script have the exact same name. Maybe that’s the prob. I’ll try that…

No, the problem is that you are not allowed to call GetComponent in the initialization of a script variable. (ie. in the same statement as a “var xxx …” outside any function.)

The solution is even simpler than the explanation above :smile: :

var zoneTarget : DoorZone;
zoneTarget = gameObject.GetComponent(DoorZone);

gah! thx! :smile:

the identical name thing seems to have resolved the Firefox-bin crash. off to test the pc…

Game objects do not have to be named differently from scripts. You can even have multiple game objects with the same name in the same scene.

naming was the only thing I changed and the Firefox-bin crash went away. still no joy on the pc but that may be unrelated.

btw the script reference GetComponent example has it shown when a var is declared. it works but throws the exception. big deal or don’t worry about it?

Our scripting examples should show proper and functioning code, please log a bug so we can track and fix that doc error, thanks.

The example shows usage of GetComponent in a local variable declaration, which is allowed. (The var statement is inside a function body.) You will only get the error when using it to initialize variables defined outside any functions.

Thanks for the clarification Keli, I hadn’t yet checked the doc page myself to verify…

ah, that wasn’t clear to me when i looked. ignore my bug report then. is the exception just left over from a prior version? the script works (on the Mac at least).