- Home /
Getcomponent null reference exception
Why am I getting a null reference exception when I call the hear noise function? NullReferenceException: Object reference not set to an instance of an object
this class is attached to a crate object and when it falls it calls the enemy object to come to it.
public class Crate : MonoBehaviour {
public AudioClip collisionNoise;
EnemyCylinder EC;
//turns on alien hear sound.
void OnCollisionEnter(Collision other)
{
AudioSource.PlayClipAtPoint(collisionNoise, transform.position);
//BroadcastMessage("HearNoise", this.transform.position);
EC = GetComponent<EnemyCylinder>();
EC.HearNoise(this.transform.position);
}
}
Answer by Jamora · Mar 02, 2014 at 01:15 PM
There is no EnemyCylinder script on the GameObject. You need to have a reference to an object that has the EnemyCylinder script. I would assume it is on the colliding gameobject.
Oh so getcomponent only works accessing scripts on the same gameobject?
@book yes. You are correct. $$anonymous$$ore specifically, it acesses scripts on the specified gameobject.
GetComponent() is the same as this.gameObject.GetComponent();
But you may access components on different gameObjects as well. In your code, other.gameObject.GetComponent() will get the script from the colliding gameobject.
Thanks jamora! I figured it out now! GameObject.Find("Cylinder").GetComponent().HearNoise(this.transform.position);