首页 > 解决方案 > 在 C#/Unity 中转换类型的问题

问题描述

我正在开发一个带有四个 UI Button 对象的画布的 Unity 项目。当我加载画布时,我希望脚本检查每个 Button 并查看本地驱动器中是否保存了相应的图像文件,如果有,则在 Button 上显示该图像 - 这是通过 GetPictureandShowIt() 实现的,它适用于单个按钮。

我遇到的问题是尝试循环浏览每个不同的按钮时。下面的脚本成功地正确循环通过按钮名称(所有这些都设置了必要的标签),但我无法使用适当的名称设置按钮变量:button = getCount[ButtonNumber]; 因此 GetPictureandShowIt() 方法无法将图像应用到下一个按钮。我收到无法将类型 'UnityEngine.GameObject' 隐式转换为 'UnityEngine.UI.Button' 的错误

我在 Unity/C# 上还是比较新的,所以如果这是一个直截了当的答案,我深表歉意。

public class LoadImages : MonoBehaviour
{    
    public Button button;
    public FloatVariable FrameNumber;
    public StringVariable GalleryName;
        
    int ButtonNumber = 0;
    int ButtonMax;
    private GameObject[] getCount;

    void Start()
    {        
        getCount = GameObject.FindGameObjectsWithTag("Frame");
        ButtonMax = getCount.Length;         
        
        while (ButtonNumber <= ButtonMax)
        {
            button = getCount[ButtonNumber];
            GetPictureAndShowIt();
            Debug.Log("Frame#: " + getCount[ButtonNumber]);
            FrameNumber.value++;
            ButtonNumber++;
        }
   }
...

标签: c#unity3d

解决方案


随着GameObject.FindGameObjectsWithTag("Frame");你得到一个GameObject不是Button类型。检查文档

也许你需要: button = getCount[ButtonNumber].GetComponent<Button>();如果按钮组件在那个游戏对象中。


推荐阅读