How to use "OnClick.AddListener" on multiple GameObjects in one Frame

Viewed 3049

I'm pretty new to Unity and C# scripting.

In my scene I have four buttons. I declared them in my script as public and put the items (on type Button) via drag and drop in my inspector in unity. Depending on which button is clicked, i want my program to do something. You can see in the script below what I've done. That scripts works perfectly just like I want it to.

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Example : MonoBehaviour
{
    public Button Left;
    public Button Right;
    public Button Starten;
    public Button Zurueck;

    private void Start()
    { 
        loadRezept(0);
        Right.onClick.AddListener(iterationUp);
        Left.onClick.AddListener(iterationDown);
        Starten.onClick.AddListener(starten);
        Zurueck.onClick.AddListener(zurueck);
    }


... (here are the methods "iterationUp" and so on...)

This script work perfectly. But now there is my question: how can I do the same on using gameobjects?

If I just change the type "Button" to "GameObject" I don't have the possibility to use "onClick.AddListener". I don't want a script for every single gameobject. I just want something like I posted above.

1 Answers

GameObject itself has no such events.


Sounds like what you are asking for is a custom UnityEvent

You can create your own component like e.g.

public class HighlightController : MonoBehaviour
{
    public UnityEvent OnHighlight;

    // Somewhere Invoke the event e.g.
    public void SetHighlighted()
    {
        OnHighlight.Invoke();
    }
}

where you can add listeners now either via code or via the Inspector (just like the onClicked).

So put this on your GameObjects and then e.g. have fields like

[SerializeField] private HighlightController highlight;
//etc...

private void Awake()
{
    highlight.OnHighlight.AddListener(HandleHighlight);
    //etc...
}

private void HandleHighlight ()
{
    ...
}

// Make sure to cleanup listeners when not needed anymore
private void OnDestroy()
{
    highlight.OnHighlight.RemoveListener(HandleHighlight);
    //etc...
}

Or yes as mentioned as simple event could do the same without the serialization:

public class HighlightController : MonoBehaviour
{
    public event Action OnHighlight;

    public void SetHighlighted ()
    {
        OnHighlight?.Invoke();
    }
}

and do

private void Awake()
{
    highlight.OnHighlight += HandleHighlight;
}

private void OnDestroy ()
{
    highlight.OnHighlight -= HandleHighlight;
}
Related