Declaring a variable and then using it says it's an unknown identifier

So I did this

#pragma strict

function Awake() {

var enemyStats : Stats.js = gameObject.GetComponent(Stats.js);


}


if (enemyStats.EnemyName === "Rat"){

	print("My hand is a dolphin");

};

But it keeps returning the error BCE0005: Unknown identifier: ‘enemyStats’.

Please help me, Answers.Unity3d.com, you’re my only hope.

Well, first of all let's get the silly question out of the way: you've declared a variable that request for a game object, did you actually assign this object on the inspector? Also, this is untested code but try declaring the var outside of the awake function, something like this: var enemyStats:GameObject; function Awake() { enemyStats.GetComponent(Stats).nameOfFunctionYouWantToCall(); if (enemyStats.EnemyName === "Rat"){ print("My hand is a dolphin"); }; }

1 Answer

1

AlejandroGorgal is right.

Also, this is untested code but try declaring the var outside of the awake function, something like this:

The problem with your code is that when a variable is declared in a block “{…}”, it only exists in that block and only as long as that block exists. When a variable is declared in a method like “Awake()”, it gets destroyed once the method is resolved. The solution is to declare it outside any methods.