有没有一种方法可以将按钮onClick功能设置为不在Unity中的场景中的预制件上的功能? [英] 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?
推荐答案
除了将处理程序设为静态之外,您还可以找到按钮的实例:
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;
}
}
此外,您还需要在添加作为侦听器之前将委托强制转换为UnityEngine.Events.UnityAction
.
Also you need to cast the delegate to UnityEngine.Events.UnityAction
before adding is as listener.
这篇关于有没有一种方法可以将按钮onClick功能设置为不在Unity中的场景中的预制件上的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!