User interface 有没有办法将button onClick函数设置为Unity中不在场景中的预设上的函数?
我有一个在运行程序时实例化的预置。预制件不在场景中。在这个预设中有一个脚本,它有一个函数,当单击按钮时应该调用该函数。按钮在场景中。在按钮的检查器中,我拖放预置并选择要执行的函数。但在跑步时,我会遇到一个例外。按钮是否有方法引用场景中不存在的预设上的函数?除了使处理程序为静态外,您还可以找到按钮的实例:User interface 有没有办法将button onClick函数设置为Unity中不在场景中的预设上的函数?,user-interface,button,unity3d,onclick,User Interface,Button,Unity3d,Onclick,我有一个在运行程序时实例化的预置。预制件不在场景中。在这个预设中有一个脚本,它有一个函数,当单击按钮时应该调用该函数。按钮在场景中。在按钮的检查器中,我拖放预置并选择要执行的函数。但在跑步时,我会遇到一个例外。按钮是否有方法引用场景中不存在的预设上的函数?除了使处理程序为静态外,您还可以找到按钮的实例: public class MyScript: MonoBehaviour { void Awake() { Button myButton = GetRefere
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;
}
}
此外,在添加is as listener之前,您需要将委托强制转换为
UnityEngine.Events.UnityAction
。如果您有一个以编程方式实例化的预设中具有多个按钮的用户界面,您可以使用GetComponentsInChildren
访问所有按钮:
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);
}
public void onUIcreated()
{
//将事件侦听器添加到画布中的所有按钮
Button[]buttons=canvasPrefabride.GetComponentsInChildren();
对于(int i=0;i
你好,谢谢你的回答。我正试图实施你的解决方案,但我有一个问题。这里有一个链接: