Search Unity

Event when component added or removed

Discussion in 'Scripting' started by Mikeysee, Jun 22, 2014.

  1. Mikeysee

    Mikeysee

    Joined:
    Oct 14, 2013
    Posts:
    155
    Hi,

    Does anyone know of a runtime ability to listen for when a component is added or removed to a gameobject?

    What would be nice:

    gameobject.componentAdded += OnComponentAdded;
    gameobject.componentRemoved += OnComponentAdded;

    Mike
     
  2. Sharp-Development

    Sharp-Development

    Joined:
    Nov 14, 2013
    Posts:
    353
    You cant by default. But you can write a wrapper around GetComponent, for example an extension or wrapper base class which you sololy use then which fires those events.
     
  3. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    There is no such thing as removeComponent.

    That said, you can just use OnAwake and OnDestroy for the add and 'remove' events.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class TEST : MonoBehaviour {
    5.    Rect AddButton, DeleteButton;
    6.    int ID;
    7.  
    8.    void Awake () {
    9.      ID = Random.Range( 0, 1000 );
    10.      Debug.Log( "Component " + ID + " Awake (Added)" );
    11.      AddButton = new Rect( Random.Range( 0, Screen.width - 50 ), Random.Range( 0, Screen.height - 50 ), 50, 50 );
    12.      DeleteButton = new Rect( Random.Range( 0, Screen.width - 50 ), Random.Range( 0, Screen.height - 50 ), 50, 50 );
    13.    }
    14.  
    15.    void OnDestroy () {
    16.      Debug.Log( "Component " + ID + " Destroyed (Removed)" );
    17.    }
    18.  
    19.    void OnGUI () {
    20.      if ( GUI.Button( AddButton, "Add\n" + ID ) ) {
    21.        gameObject.AddComponent<TEST>();
    22.      }
    23.  
    24.      if ( GUI.Button( DeleteButton, "DEL\n" + ID ) ) {
    25.        Destroy( this );
    26.      }
    27.    }
    28. }
    Of course, these will only fire from within the component that is added or removed, not from a watcher or similar.
    But for that, you just call some code at the same time as adding or destroying the component from wherever that happens.

    Code (CSharp):
    1.     someObject.AddComponent<SomeThing>();
    2.     DoAThing();
    3.  
    4.     Destroy(GetComponent<SomeThing>())
    5.     DoAnotherThing();
    6.  
    If you wanted, you can make a manager object to handle both steps, then you just
    Code (CSharp):
    1.     ComponentManager.MyComponentAdder(targetGameObject, desiredComponentType)
    2.