Destroy a component in C#

Hi.

First, forgive me for not knowing what I’m doing.

With that said, how do I destroy a component in C#?

I’m trying to make some alterations to the CombineChildren script so that the Mesh Renderer of all the child objects is destroyed once the game starts. I am using Unity’s primitive game objects as colliders. I like having the mesh viewable in the editor so that I know where I’ve placed all my colliders. But I’d like them to disappear at runtime.

The Unity docs are in Javascript, and the CombineChildren script is in C#.

I know how to destroy a game object. But I don’t know how to just single out components.

You can destroy components similarly as GameObjects:

Destroy(gameObject.GetComponent("ComponentName"));

Where ComponentName is the name of the component you want to destroy.

1 Like

You’ve got several options:

  1. Put the objects into a layer on their own and set the layer to non renderable
  2. Set the mesh renderer for each of the objects to disabled

Are all the objects children of a parent? If so you can select them all and disable the mesh renderer with:

http://forum.unity3d.com/viewtopic.php?p=247597

Thanks for the link.

Shortly after I started this thread I started getting rid of everything in CombineChildren that I didn’t need and ended up with almost nothing except the table.

But that solution in JS worked great.

function Start() {
 

   var transforms = GetComponentsInChildren (Transform);
      for (var t : Transform in transforms) {
         if(t.gameObject.GetComponent(Renderer)){
           if (t.gameObject.GetComponent(Renderer).enabled)
           {
              t.gameObject.GetComponent(Renderer).enabled = false;
           }
         }
      
   }
}

The public static function Destroy() is a key its Removes a gameobject, component or asset. reference

Examples:

// Kills the game object
Destroy (gameObject);

// Removes this script instance from the game object
Destroy (this);

// Removes the rigidbody from the game object
Destroy (rigidbody);

// Kills the game object in 5 seconds after loading the object
Destroy (gameObject, 5);

// When the user presses Ctrl, it will remove the script
// named FooScript from the game object
function Update () {
if (Input.GetButton (“Fire1”) && GetComponent (FooScript))
Destroy (GetComponent (FooScript));
}

I’d like to point out that the unity docs are not just in javascript. Theres an option at the top that allows you to switch the language the examples are shown in.

This thread is way old.

–Eric