簡體   English   中英

在 C# / Unity 中轉換類型的問題

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

我正在開發一個具有 canvas 和四個 UI Button 對象的 Unity 項目。 當我加載 canvas 時,我希望腳本檢查每個 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>(); 如果按鈕組件在該游戲對象中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM