Tom
Tom

Reputation: 1095

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.

Upvotes: 3

Views: 2377

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

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.

Upvotes: 4

Related Questions