- Home /
NullReference Problem with pragma strict
I've the following problem with an UnityScript when using #pragma strict:
#pragma strict
public var SwordAniScript: AttackFlow;
function Start() { var SwordAniScript : AttackFlow =GameObject.Find("SwordAni").GetComponent(AttackFlow) as AttackFlow; }
function Update() { if (SwordAniScript.canAttack) { //do Code } }
When I compile the script I doesn't get any error or warning.
But when the script will be executed I get an error: NullReferenceException: Object reference not set to an instance of an object at this line "if (SwordAniScript.canAttack) ". The AttackFlow script is also written in JS and canAttack is declared as:
public var canAttack: boolean = true ;
Can somebody help me with this annoying problem ?
Thank you in advance.
Answer by Peter G · Jan 15, 2011 at 08:41 PM
First, to clarify what NullReference exceptions mean. A NullReference means that Unity looked for an object in a reference type (any class, but not a struct) and it found null instead of an instance of your object.
In your case, Unity checked SwordAniScript, and if found nothing there, or null. Well then why?
Your local declaration of SwordAniScript appears to be masking your global definition. So you are creating a new variable called SwordAniScript and then finding the component. In that case, you probably are finding the component you want, but you are assigning it to the wrong variable which will go out of scope as soon as your function returns. Remove the var
keyword to access the global variable and that should solve your problem.
Or, if that doesn't work, there is also a chance that "SwordAni" doesn't have a AttackFlow script attached to it, or that you do not have an object in your scene that exactly matches your string, "SwordAni".
Remove the var keyword to access the global variable --> This solved it. Brilliant member and a really good explanation!
Your answer
Follow this Question
Related Questions
NullReferenceException: Object reference not set to an instance of an object ..... 1 Answer
how would I make an array of different scripts 1 Answer
Static Dictionary not initializing properly 1 Answer
I'm having more problems accessing a variable from another script in c# 2 Answers
NullReferenceException 1 Answer