【问题标题】:Unity - C# - attach GameObject to public Button CommunicationButton;Unity - C# - 将 GameObject 附加到公共按钮 CommunicationButton;
【发布时间】:2016-11-18 11:41:35
【问题描述】:

我无法解决这个问题,我希望有人知道该怎么做。

我有什么

画布上的按钮和文本字段,参见图片:

我有一个名为 HumanInstructions 的脚本,它的初始化如下:

public Text CommunicationMessage;
public Button CommunicationButton;

现在我可以通过在下拉菜单中选择按钮/文本字段来在检查器中分配相应的游戏对象。

我想要的,是通过脚本选择游戏对象。文本字段称为 CrazyMsg,按钮称为 CommunicationButton。所以我想要这样的东西:

public override void OnAwake ()
{
    CommunicationMessage = GameObject.find("CrazyMsg");
    CommunicationButton = GameObject.find("CommunicationButton");
}

它不起作用。救命!

【问题讨论】:

    标签: c# unity3d nullreferenceexception gameobject


    【解决方案1】:

    它是GameObject.Find 而不是GameObject.find。找到 GameObject 后还需要获取 Component。

    public Text CommunicationMessage;
    public Button CommunicationButton;
    
    void Start()
    {
        CommunicationMessage = GameObject.Find("CrazyMsg").GetComponent<Text>();
        CommunicationButton = GameObject.Find("CommunicationButton").GetComponent<Button>();
    
        //Register Button Click
         CommunicationButton.onClick.AddListener(() => buttonClickCallBack());
    }
    
    //Will be called when CommunicationButton Button is clicked!
    void buttonClickCallBack()
    {
       CommunicationMessage.text = ....
    }
    

    您也可以使用CommunicationButton.onClick.AddListener(delegate { buttonClickCallBack(); });CommunicationButton.onClick.AddListener(buttonClickCallBack); 注册按钮

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 2022-12-16
      • 2014-01-31
      • 2022-07-06
      • 2015-08-17
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 2023-02-18
      相关资源
      最近更新 更多