Reputation: 1095
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.
_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
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