Tom Tom - 2 days ago 4
C# Question

GetComponent returning null

In both Unity 5.4/5.5, I'm having an issue with GetComponent not returning the CharacterController of my GameObject for some reason. After I restart Unity, it works again.

enter image description here

_MAIN runs this script:

private GameObject frog;
private CharacterController controller;

void Start () {
frog = GameObject.Find ("Frog");
controller = frog.GetComponent<CharacterController> ();

Debug.Log(controller); // returns null
}

void Update () {
if (controller.isGrounded) {
// error is thrown
}
}


After the
controller
is referenced in Update, I get the error:


MissingComponentException: There is no 'CharacterController' attached to the "Frog" game object,


FYI,
frog
is returning the GameObject just fine.

Answer

Instead of using GameObject.Find("Frog") try using GameObject.FindWithTag("Frog") and add the tag "Frog" to the frog object.

The reason you are having this happen is somehow, somewhere, a 2nd object named "Frog" is added to the scene. When this happens Unity will randomly pick one of the two objects it found, this will cause it to work sometimes but not other times.

By switching to a tag you make it more likely that the object will be identified uniquely.

Comments