Rango
Rango

Reputation: 229

Is there a way to set a button onClick function to a function on a prefab that is not in a Scene in Unity?

I have a prefab that instantiate on running the program. The prefab is not already in the scene. On this prefab there is a script with a function that should be called when a button is clicked.The button is in the scene. In the button's inspector I drag and dropped the prefab and chose the function to execute. But on running, I get an exception. Is there a way for the button to reference a function on a prefab that is not in the scene?

Upvotes: 1

Views: 7742

Answers (2)

Claus
Claus

Reputation: 5742

If you have a user interface with multiple buttons in a prefab instantiated programmatically, you can use GetComponentsInChildren to access all the buttons:

public void onUIcreated()
{
    // Add event listeners to all buttons in the canvas
    Button[] buttons = canvasPrefab.GetComponentsInChildren<Button>();
    for (int i = 0; i < buttons.Length; i++)
    {
        string identifier = buttons[i].name;
        buttons[i].onClick.AddListener(delegate { OnButtonTapped(identifier); });
    }
}

public void OnButtonTapped(string identifier)
{
    Debug.Log("Pressed button:" + identifier);
}

Upvotes: 2

Jerry Switalski
Jerry Switalski

Reputation: 2720

Apart from making handler static, you can just find the instance of the button:

public class MyScript: MonoBehaviour
{
    void Awake()
    {
        Button myButton = GetReferenceToButton();
        myButton.onClick.AddListener ((UnityEngine.Events.UnityAction) this.OnClick);
    }

    public void OnClick()
    {
        Debug.Log("Clicked!");
    }

    private Button GetReferenceToButton()
    {
        Button btn = null;
        //Find it here
        return btn;
    }
}

Also you need to cast the delegate to UnityEngine.Events.UnityAction before adding is as listener.

Upvotes: 4

Related Questions