Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 224
Tom Avatar asked Dec 14 '25 18:12

Tom


1 Answers

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.

like image 171
Scott Chamberlain Avatar answered Dec 17 '25 08:12

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!