c# - 在 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++;
}
}
...
解决方案
随着GameObject.FindGameObjectsWithTag("Frame");
你得到一个GameObject
不是Button
类型。检查文档
也许你需要:
button = getCount[ButtonNumber].GetComponent<Button>();
如果按钮组件在那个游戏对象中。
推荐阅读
- python-3.x - PyQt5:style().polish() 导致分段错误?
- javascript - 如何使用 react native snap carousel 通过分页实现此视图?
- node.js - CORS 阻止访问资源:如何在 Firebase 云功能中修复?
- rhel - vncserver:找不到“/bin/vncpasswd”
- javascript - 为什么我的第二个脚本不知道第一个脚本中的功能?
- ruby-on-rails - 使用嵌套数据调用 API,得到“TypeError:没有将 String 隐式转换为 Integer”
- google-cloud-platform - Google Cloud 警报政策 - 在文档正文中包含错误消息
- c# - 为不同的平台、架构和 .net 版本创建 Nuget 包
- regex - 红宝石正则表达式。限制最小和最大字符串长度
- firebase - Firestore Stream 已关闭,状态为 UNAVAILABLE