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

Ran*_*ngo 4 c# user-interface button unity-game-engine

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

我试着在检查器中拖放按钮,但引擎不会让我.我尝试通过标签找到它,但我得到一个异常"不能隐式转换类型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");

    }
}
Run Code Online (Sandbox Code Playgroud)

Pro*_*mer 5

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

shootButton = GameObject.FindGameObjectWithTag ("ShootButton") as Button;
Run Code Online (Sandbox Code Playgroud)

你不能Button像这样将Component()强制转换为GameObject.您必须使用从GameObject GetComponent获取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);
Run Code Online (Sandbox Code Playgroud)

然后拖动ButtonshootButton 槽:

在此输入图像描述

要么

从脚本中获取引用:

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

shootButton = GameObject.FindGameObjectWithTag ("ShootButton") as Button;
shootButton.onClick.AddListener ((UnityEngine.Events.UnityAction)this.OnShootButtonClick);
Run Code Online (Sandbox Code Playgroud)

shootButton = GameObject.FindGameObjectWithTag("ShootButton").GetComponent<Button>();
shootButton.onClick.AddListener(() => OnShootButtonClick());
Run Code Online (Sandbox Code Playgroud)