- Home /
How do I check if a game object exists?
Hello. I'm trying to run a check for null before the object "shotSaw" is removed. There are multiple things that can destroy the saw, so I need to make sure scripts do not error when there is no saw to delete. However, checking for null still doesn't prevent the error. Is this a problem with my logic, or should I check for something besides null?
var force : int;
var shootPosition:Transform;
var charging : boolean;
var shotSaw : GameObject;
var idleSound : AudioClip;
var shotSound : AudioClip;
var spinSpeed : float;
function Start () {
}
function FixedUpdate ()
{
print (shotSaw.transform.localScale.x);
if (Input.GetButton ("Fire1"))
{
if (charging != true)
{
shotSaw = Instantiate (saw, transform.position, shootPosition.rotation);
charging = true;
}
if (charging == true)
{
if(!audio.isPlaying)
{
audio.PlayOneShot(idleSound);
audio.Play();
}
if (shotSaw != null)
{
shotSaw.rigidbody2D.AddTorque (spinSpeed/2);
shotSaw.rigidbody2D.gravityScale = 0;
shotSaw.collider2D.isTrigger = true;
shotSaw.transform.position = Vector3(shootPosition.position.x,shootPosition.position.y,shootPosition.position.z);
}
}
}
else
{
if (charging == true)
{
if (shotSaw != null)
{
if (shotSaw.transform.localScale.x > 0.0280)
{
audio.Stop();
shotSaw.rigidbody2D.gravityScale = 1;
shotSaw.collider2D.isTrigger = false;
shotSaw.rigidbody2D.AddForce(shootPosition.right * force);
charging = false;
audio.Stop();
}
else
{
if (shotSaw != null)
{
Destroy(shotSaw);
}
}
}
}
}
}
Any help would be appreciated.
For simplicity the following two lines are identical
if (shotSaw)
if (shotSaw != null)
Not seeing the error in your code.
For efficiency you only need to check if shotSaw exists once at the beginning. The way Unity executes code is very linear, no other code will run until the current Update is finished.
Thanks! Not sure why the other logic wasn't checking out, but checking for shotsaw once at the start of the code works perfectly.
Answer by SparkZWolf · Jun 16, 2014 at 01:08 PM
Check for your object once at the start of the code. Thanks, Bored Mormon!
Your answer
Follow this Question
Related Questions
If String is in List Then... 2 Answers
if(Find.Child("thing");{ 3 Answers
If/else statements working one way, and not the other 0 Answers
Why is my array null? 0 Answers