【问题标题】:Get Buttons and store them in an array获取按钮并将它们存储在数组中
【发布时间】:2017-10-13 01:54:03
【问题描述】:

所以我在画布上放置了 6 个 UI 按钮,即“Tier 1”-“Tier 6” 我想将所有“Tier 1”-“Tier 6”作为按钮存储在数组中 所以我可以通过 c# 设置可交互的对象

这是我的代码

// Buildings
[Header("Buildings")]
public Button [] buildingTiers;
public int numOfBuildingTiers = 6; // Number of building tier buttons;

// ==============================================================
void Awake()
{
    buildingTiers = new Button[numOfBuildingTiers];

    for (var i = 1; i < numOfBuildingTiers; i++)
    {
        GameObject _buildingTiers = GameObject.Find ("Tier " + i).GetComponent<Button> (); // This is line 37
        buildingTiers [i] = _buildingTiers; // This is line 38
        buildingTiers [i].interactable = false;
    }
}

我收到了这个错误

Assets/Octa Interactive 的 Assets/Codes/Main.cs(37,71):错误 CS0029: 无法隐式转换类型UnityEngine.UI.Button' to UnityEngine.GameObject'

Assets/Octa Interactive 的 Assets/Codes/Main.cs(38,33):错误 CS0029: 无法隐式转换类型UnityEngine.GameObject' to UnityEngine.UI.Button'

【问题讨论】:

    标签: c# arrays user-interface button unity3d


    【解决方案1】:

    试试这样:

    // Buildings
    [Header("Buildings")]
    public Button [] buildingTiers;
    public int numOfBuildingTiers = 6; // Number of building tier buttons;
    
    // ==============================================================
    void Awake()
    {
        buildingTiers = new Button[numOfBuildingTiers];
    
        for (var i = 1; i <= numOfBuildingTiers; i++)
        {
            Button _buildingTiers = GameObject.Find ("Tier " +    i).GetComponent<Button> (); // This is line 37
            buildingTiers [i] = _buildingTiers; // This is line 38
            buildingTiers [i].interactable = false;
        }    
    }
    

    您正在获取 Button 组件并将其“存储”在 GameObject 变量中。

    此外,您只添加了从第 1 层到第 5 层的按钮,也为您解决了这个问题。 &lt;= 而不是 &lt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 2013-05-09
      • 2015-06-27
      • 2022-07-27
      相关资源
      最近更新 更多