You can use AddComponent() and Destroy() methods to add and destroy a gameObject by C# script. Let take a look at both of them.
Adding Components
An example of adding a Ridigbody component to a gameObject is given below:
We can also use AddComponent(typeof(Type)) of method where Type is is the type of component we want to add.
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:
We can directly use Destroy() method in a gameObject and it will remove that component and all its references.
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.
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
Post a Comment