简体   繁体   English

在 C# / Unity 中转换类型的问题

[英]Issues with Converting Types in C# / Unity

I'm working on a Unity project that has a canvas with four UI Button objects.我正在开发一个具有 canvas 和四个 UI Button 对象的 Unity 项目。 When I load the canvas, I want the script to check each Button and see if there is a corresponding image file saved in the local drive and then, if so, display that image on the Button - this is achieved with GetPictureandShowIt(), which works for a single button.当我加载 canvas 时,我希望脚本检查每个 Button 并查看本地驱动器中是否保存了相应的图像文件,如果有,则在 Button 上显示该图像 - 这是通过 GetPictureandShowIt() 实现的,它适用于单个按钮。

The issue I'm having is when trying to cycle through each of the different buttons.我遇到的问题是尝试循环浏览每个不同的按钮时。 The below script successfully cycles through the button names properly (which have all been set with the necessary tag), but I can't set the button variable with the appropriate name using: button = getCount[ButtonNumber];下面的脚本成功地循环通过按钮名称正确(所有这些都设置了必要的标签),但我无法使用适当的名称设置按钮变量: button = getCount[ButtonNumber]; and therefore the GetPictureandShowIt() method can't apply the image to the next button.因此 GetPictureandShowIt() 方法无法将图像应用到下一个按钮。 I get an error of Cannot implicitly convert type 'UnityEngine.GameObject' to ' UnityEngine.UI.Button' .我收到无法将类型 'UnityEngine.GameObject' 隐式转换为 'UnityEngine.UI.Button' 的错误

I'm still relatively new at Unity/C#, so apologies if it is a straightforward answer.我在 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++;
        }
   }
...

With GameObject.FindGameObjectsWithTag("Frame");使用GameObject.FindGameObjectsWithTag("Frame"); you are getting a GameObject not a Button type.你得到一个GameObject而不是Button类型。 Check the docs检查文档

Maybe you need to: button = getCount[ButtonNumber].GetComponent<Button>();也许你需要: button = getCount[ButtonNumber].GetComponent<Button>(); if the button component is in that gameobject.如果按钮组件在该游戏对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM