从Unity中的脚本获取对按钮的引用

时间:2016-09-22 07:44:03

标签: c# user-interface button unity3d

脚本附加到不在场景中的预制件。按钮有标签。

我尝试在检查器中拖放按钮,但引擎不会让我。我尝试通过标签找到它,但我得到一个异常“不能隐式转换类型UnityEngine.GameObject到UnityEngine.UI.Button”,当我转换时,我得到一个异常,我无法通过内置转换转换这些类型。 一些帮助? 如何获得对按钮的引用? 这是代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class TankShooting : MonoBehaviour {

    private Transform ShootingCameraTransform;
    private PlayerTankMovement playerTankMovement;
    public Button shootButton;


    // Use this for initialization
    void Start () {

        shootButton = GameObject.FindGameObjectWithTag ("ShootButton") as Button;
        shootButton.onClick.AddListener ((UnityEngine.Events.UnityAction)this.OnShootButtonClick);

        playerTankMovement = GetComponent<PlayerTankMovement> ();
        Transform t = transform;
        foreach (Transform tr in t)
        {
            if (tr.tag == "ShootingCamera") 
            {
                ShootingCameraTransform = tr.transform;
            }
        }
    }

    // Update is called once per frame
    void Update () {

    }

    public void OnShootButtonClick()
    {
        Debug.Log ("Success");

    }
}

1 个答案:

答案 0 :(得分:5)

查看您的代码,还有另一个问题:

shootButton = GameObject.FindGameObjectWithTag ("ShootButton") as Button;

你不能像这样将组件(Button)强制转换为GameObject。您必须使用GetComponent从GameObject获取Button组件。

  

我无法在检查器中拖放按钮,当我找到它时   通过标签我无法将其从GameObject转换为Button

那是因为您拖动到shootButton插槽的GameObject不是Button或者没有附加Button组件。必须有Button组件才能将其拖动到Button(shootButton)插槽。

您必须创建一个Button,然后将该Button拖到shootButton位置。

您可以先执行删除

shootButton = GameObject.FindGameObjectWithTag ("ShootButton") as Button;
shootButton.onClick.AddListener ((UnityEngine.Events.UnityAction)this.OnShootButtonClick);

然后将Button拖到shootButton广告位:

enter image description here

从脚本中获取引用:

如果您想从脚本执行此操作,请替换

shootButton = GameObject.FindGameObjectWithTag ("ShootButton") as Button;
shootButton.onClick.AddListener ((UnityEngine.Events.UnityAction)this.OnShootButtonClick);

shootButton = GameObject.FindGameObjectWithTag("ShootButton").GetComponent<Button>();
shootButton.onClick.AddListener(() => OnShootButtonClick());