Home > Software design >  Is it possible to add a onClick() Event action(in GameObject dropdown) without adding new script in
Is it possible to add a onClick() Event action(in GameObject dropdown) without adding new script in

Time:09-22

I have a Hololens Slate which comes with Pressable Button to close the slate.

However, when the slate is closed, it is disabled but not destroyed because in the Events section in Interactable script, GameObject.SetActive() is set by default :

Interactable script selection

I want to destroy the slate after clicking this button. I know I can do this by making a script, attach the slate prefab to the script(or take the parent of the button till I get slate as parent game object), call the function, and use GameObject.Destroy().

But I want to understand how the GameObject dropdown in Interactable script is getting populated :

GameObject dropdown in Event section for Slate

I understand that the other dropdowns like Transform, Follow me toggle, Solverhandler, etc are displayed because they are attached to the Slate. But how does the GameObject option is available? This seems a basic thing, but I would like to be sure about how it is coded. And if it is possible to add my new action in the Gameobject dropdown, if so, how?

I spent time looking at the scripts of Interactable and others, but I am a beginner in C# and was not able to see where is the code which does this. Any input will help me, Thanks in advance

CodePudding user response:

No you can't because Object.Destroy is static and in UnityEvent (which Interactable.OnClick uses) via the Inspector you can only select instance methods.

You at lest need a minimal component like

public class ObjectDestroyer : MonoBehaviour
{
    public void DestroyObject()
    {
        Destroy(this.gameObject);
    }
}

or if you don't want to do it via the Inspector but automatically

public class ObjectDestroyer : MonoBehaviour
{
    // store the itneractable reference
    [Tootltip("If not provided uses the Interactable on this GameObject")]
    [SerialzieField] private Interactable _interactable;

    // Optionally provide a different target, otherwise destroys the Interactable
    [Tooltip("If not provided destroys the GameObject of the Interactable")]
    [SerializeField] private GameObject _targetToDestroy;

    private void Awake()
    {
        // use get component as fallback if no Interactable was provided
        if(!_interactable) _interactable = GetComponent<Interactable>();

        // attach the callback on runtime (won't appear in the inspector)
        _interactable.OnClick.AddListener(DestroyObject);
    }

    private void DestroyObject()
    {
        // destroy the object of the interactable if no target was provided
        if(!_targetToDestroy) _targetToDestroy = _interactable.gameObject;

        Destroy(_targetToDestroy);
    }
}
  • Related