[SOLVED] Destroy(GetComponent(this))

I’m trying that when a script’s timer reaches 0, remove the component.
This is what I have:

using UnityEngine;
using System.Collections;

public class BuffScript : MonoBehaviour
{
        public float duration;
        public float durationRemaining;
       
        protected internal HealthScript health;
       
        protected virtual void Awake ()
        {
                health = GetComponent<HealthScript> ();
        }

        void Update ()
        {
                if (durationRemaining > 0) {
                        durationRemaining -= Time.deltaTime;
                } else {
                        RemoveBuff (this);
                }
        }
       
        public void RemoveBuff (string buff)
        {
               
                Destroy (GetComponent (buff));
        }
       
        public void RemoveAllBuffs ()
        {
                BuffScript[] buffs = GetComponents<BuffScript> ();
                foreach (BuffScript buff in buffs) {
                        Destroy (buff);
                }
        }
}

What error is it crapping out?

this refers to the GameObject the script is attached to and not the script itself.

Mrmmm… nope.

‘this’ refers to the object inwhich the method has scope (if there is an object… static methods have no object to be scoped to, thusly a compiler error will occur).

If in a ‘MonoBehaviour’, ‘this’ will be your script.

this.gameObject is the GameObject.

You say:

RemoveBuff(this);

But RemoveBuff expects a string, and that string is used to GetComponent.

But ‘this’ is a component already, you should probably be getting a compiler error like:

Or something like:

Or both.

You should do something like:

        void Update ()
        {
                if (durationRemaining > 0) {
                        durationRemaining -= Time.deltaTime;
                } else {
                        Destroy(this);
                }
        }

Or even have some overloads of RemoveBuff like so:

//removes this buff
public void RemoveBuff()
{
    Destroy(this);
}

//removes a buff if it's on the same gameobject as this
public void RemoveBuff(BuffScript buff)
{
    if(buff.gameObject == this.gameObject) Destroy(buff);
}
2 Likes

@lordofduct , Interesting because in my original code I have “this.name” and when I print it, it says the monsters name and not the script and nothing is destroyed.

Hi, I think that instead of removing the component, you better (don’t know if it is really better) desactivate it
GetComponent().enabled =true;

That’s because this.name uses the inherited Object.name property. lordofduct’s post is correct.

–Eric

1 Like

That explains it.
Thanks guys.