How do I check if there's a component on an game object and remove it?

I have components attached to a game object that I need to remove every time the level is unloaded. This is the code I have so far to find the components on the game object:

Component[] components = myGameObject.GetComponents(typeof(Component));
      foreach (Component component in components) {
              Debug.Log (component);
      }

Now I need to add a conditional statement in there checking if the component is a certain kind of component called ‘O_MoveTo’ in my program.

But, I can’t just use a string, so I’m not sure how to write out that if statement:

if (component.name == "O_MoveTo") {
   //This doesn't work
}

P.S, I tried this as well:

      if (component.GetType () == O_MoveTo) { 
           Debug.Log (component);
       }

I get a ‘Expression denotes a type where a variable, value or method group was expected’ error with that…

You want typeof(O_MoveTO) I think. alternatively, you could use: GetComponents<O_MoveTo> , which would return an array of components attached that match.

1 Like
        var components = myGameObject.GetComponents<Component>();
        foreach (var component in components) {
            if (!(component is O_MoveTo)) {
                Debug.Log(component);
            }
        }
1 Like

Oooh, okay the ‘is’ keyword is used here, that makes it a little bit simpler…

I ended up using this:

if (component.GetType ().ToString () == myTestString)

Cool, I mean as long as it’s working. As is often the case, there are many ways to get a result :slight_smile:

yeah “is” is for checking if types are the same. A other option would be to use the “as” keyword to try and cast the object. if the cast fails it will result in null.

uh huh :slight_smile: typeof(varible) returns its type and GetComponents returns an array of Type, too :wink:

This would be faster and more robust.

MyComponent[] myComponents = GetComponents<MyComponent>();
foreach (MyComponent myComponent in myComponents){
    // Do Something
}