- Home /
Question by
Jan_Julius · Oct 14, 2014 at 11:48 AM ·
runtimeboolother script
Missing reference to object
How can I make this only run once, because it seems like it searches for the object after it removed it, I'll show you what I mean.
In script of main object:
FixedUpdate(){
if(Match){
bool doOnce = true;
if(doOnce){
doOnce = false;
Hex hex;
hex = transform.Find("Hex").gameObject.transform.GetComponent<Hex>();
hex.DetachHex();
}
transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(0.1f, 0.1f, 0.1f), 1*Time.deltaTime );
}
}
in hex:
public void DetachHex(){
transform.parent = null;
}
But when I run the code this happens:
NullReferenceException: Object reference not set to an instance of an object MainScript.FixedUpdate ()
Comment
Best Answer
Answer by HarshadK · Oct 14, 2014 at 11:57 AM
Do not declare your doOnce variable inside your if statement, rather do it outside of any method. Currently whenever the match condition is true it is setting the doOnce to true and executing whatever is inside the if(doOnce), which means each time on match condition is true.
Change it to:
bool doOnce = true; // Now this is declared outside
FixedUpdate(){
if(Match){
if(doOnce){
doOnce = false;
Hex hex;
hex = transform.Find("Hex").gameObject.transform.GetComponent<Hex>();
hex.DetachHex();
}
transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(0.1f, 0.1f, 0.1f), 1*Time.deltaTime );
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613165053im_/https://answers.unity.com/themes/thub/images/avi.jpg)