當我單擊其中一個時,我試圖更改“分頁”的所有按鈕的顏色。所以我標記了這些按鈕PageButton
通常,我FindGameObjectsWithTag用來獲取具有特定標簽的元素集合。但即使將它轉換為Button它不起作用/顯示錯誤,除了FindGameObjectsWithTag在建議或檔案中我沒有找到任何其他內容
private Button[] buttons;
void Start()
{
//this show me an error telling me I can't convert form UI to gameobject
buttons = GameObject.FindGameObjectsWithTag("PageButton") as Button;
foreach(Button button in buttons)
{
//my code to change every buttons color will go here
}
}
uj5u.com熱心網友回復:
您不能簡單地強制轉換GameObject為Button. 你需要使用GetComponent!
您可以直接執行并使用
var objs = GameObject.FindGameObjectsWithTag("PageButton");
buttons = new Button[objs.Length];
for(var i = 0; i < objs.Length; i )
{
buttons[i] = objs[i].GetComponent<Button>();
}
或使用LinqSelect并執行
using System.Linq;
...
buttons = GameObject.FindGameObjectsWithTag("PageButton").Select(obj => obj.GetComponent<Button>()).ToArray();
或者,您也可以反過來,使用 找到Button場景中的所有s FindObjectsOfType,然后按標簽過濾,例如
var allButtons = FindObjectsOfType<Button>();
var taggedButtons = new List<Button>();
foreach(var button in allButtons)
{
if(button.CompareTag("PageButton"))
{
taggedButtons.Add(button);
}
}
buttons = taggedbuttons.ToArray();
你可以再次使用LinqWhere來縮短它
buttons = FindObjectsOfType<Button>().Where(button => button.CompareTag("PageButton")).ToArray();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349298.html
上一篇:如何匹配另一個物件的旋轉增量?
