Search Unity

Script Help

Discussion in 'Scripting' started by Nixel2013, Aug 2, 2019.

  1. Nixel2013

    Nixel2013

    Joined:
    May 9, 2019
    Posts:
    143
    Can you destroy a script with the same script?

    I mean, with an ontriggerentrer an action passes, then can I delete ONLY the script without destroying the entire object?

    and how?
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Yes, a MonoBehaviour class represents a component on the GameObject, not the GameObject itself.

    If you call "Destroy(this)" the component is destroyed. "this" is a C# keyword that serves as a reference to the current class instance.

    If you call "Destroy(gameObject)" the whole GameObject is destroyed. "gameObject" is a MonoBehaviour-provided reference to the GameObject that "this" component is attached to.
     
    Last edited: Aug 2, 2019
  3. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Instance. This reference to currently executing class instance. A class may have multuple instances. To reference the class itself, call this.GetType();
     
    LiterallyJeff likes this.
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    yes, that's an important distinction.
     
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    On the forum we often throw around the term "script" casually, but mean a few different things depending on context. As already touched on, you generally have a MonoBehaviour class and then instances of that MonoBehaviour class attached to GameObjects.

    Yes an instance of a MonoBehaviour class can destroy another instance of the same MonoBehaviour class (or even itself). Just get a reference to the instance you want to destroy. You can also disable the instance of that class, which is often preferable (since you give yourself the option to re-enable it later).
     
    Last edited: Aug 2, 2019
    Nixel2013 likes this.