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

喜你入骨 提交于 2019-12-11 05:07:36

问题


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?


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/39616824/is-there-a-way-to-set-a-button-onclick-function-to-a-function-on-a-prefab-that-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!