How do you remove a component from a GameObject?

I have several GameObjects that have an Animator component attached to them. When a certain condition is met in the game, I need to completely delete the animator component
from the GameObjects.

private var cubeBlue : GameObject;

private var cubeRed : GameObject;

private var cubeYellow : GameObject;

private var cubeOrange : GameObject;

private var cubeGreen : GameObject;

private var RigidBody : Rigidbody;

cubeBlue = GameObject.Find(“BlueCube”);

cubeGreen = GameObject.Find(“GreenCube”);

cubeYellow = GameObject.Find(“YellowCube”);

cubeOrange = GameObject.Find(“OrangeCube”);

cubeRed = GameObject.Find(“RedCube”);

cubeRed.gameObject.Destroy(GetComponent(Animator));

cubeOrange.gameObject.Destroy(GetComponent(Animator));

cubeYellow.gameObject.Destroy(GetComponent(Animator));

cubeGreen.gameObject.Destroy(GetComponent(Animator));

cubeBlue.gameObject.Destroy(GetComponent(Animator));

1 Answer

1

I actually just got this working haha, thanks though. I used:

Destroy(cubeRed.GetComponent(Animator));

Worked like a charm.

try DestroyImmediate(component)

You understand why, yeah? Unless you specify a target GameObject, GetComponent() is relative to whatever object the script is attached to. Destroy(), on the other hand, doesn't really care.

To be honest I don't understand the method you posted, I'll research DestroyImmediate(); in the API.