3
votes

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.

1
Do you have any other GameObject called Frog in your scene? Look carefully... Also, please include the complete code of how you are using it in the Update function - Programmer
The code stops at if (controller.isGrounded) { in Update. - Tom
You can put the update function in your question - Programmer
Updated the question - Tom
That' your whole Update function code? controller variable is not being accessed/assigned from another function? Finally, did you import any model from any 3D software? - Programmer

1 Answers

4
votes

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.