How to add and remove components by C# script in unity

 You can use AddComponent() and Destroy() methods to add and destroy a gameObject by C# script. Let take a look at both of them.

components in unity


Adding Components

An example of adding a Ridigbody component to a gameObject is given below:

Code :
GameObject MyObject;

void Start()
{
    MyObject = GameObject.Find("MyObject");
    MyObject.AddComponent<Rigidbody>();
}

We can also use AddComponent(typeof(Type)) of method where Type is is the type of component we want to add.

Code :
MyObject.AddComponent(typeof(Rigidbody));

Removing Components

Destroy()  method is use for destroy a component for that we need to pass component which we want to destroy lets check it out in a code example:

Code :
Rigidbody rb = MyObject.GetComponent<Rigidbody>();
Destroy(rb);

We can directly use Destroy() method in a gameObject and  it will remove that component and all its references.

Code :
Destroy(MyObject.GetComponent<Rigidbody>());

You must not that Destroy() method will only mark component for destruction and it actually destroy it at end of the frame.

If there are many components of same types are attached with gameObjects. You can access all component by GetComponents method and for removing all of them then we assign reference to all component in array or list and then by Destroy() method in foreach loop.

Code :
Rigidbody[] rbs = MyObject.GetComponents<Rigidbody>();
foreach (Rigidbody rb in rbs)
{
    Destroy(rb);
}

You must note that when you remove a component it may affect behavior of other components or gameObject which depend on it. so be careful when removing a component.


Comments