C#: How do you use a scripting component to destroy the script component itself? (More info inside)

When I mean destroying itself, I do not mean for the script component to destroy a game object.

What I want is to call a script component to destroy the script component itself.

Here’s the following code:

public class Foo : MonoBehaviour {
    public void Start() {
        //Destroys Foo script component. And yes, Foo script component is "this piece of code," the code you are reading right now.
        Destroy(this.GetComponent<Foo>());
    }
}

How can it be done? I am having trouble destroying itself.

Destroy (this) should do that job. It will just destroy the Instance of script component.

1 Like

Weird how GetComponent() doesn’t work. I guess it’s because of some other codes I had.

Anyway, thanks for telling me.

You are welcome.

GetComponent can be used to get other scripts and components but not the own script. “this” represents the current Instance (i.e.) the current component.