我正在使用Visual Studio在Unity中使用C#进行编码。我试图通过使用“位置”值来选择由类制成的对象。我正在努力解释它,但是本质上我有一个名为Counties的画布,里面有几个UI对象,例如Leinster和Connacht:
我穿过那个帆布郡县的所有孩子,一一选中。
for (int i = 0; i < Counties.transform.childCount; i++)
{
Transform t = Counties.transform.GetChild(i);
Current = t.name;
}
但是,我还需要更改每个子代的一些值,因为它们在我的脚本中都有一个对应于每个子代的对象。例如,在下面的代码中,该对象对应于Leinster。
public County Leinster = new County(2630000, "NorthernIreland", "Connacht", "Munster", "Wales", 0);
我不知道该怎么做的是实际上将两者连接起来。我在对象中输入了“位置”值,这是最后一个数字。对于Leinster来说,它是0,因为那是画布县中的第一个孩子,而下一个(Connacht)将是1,依此类推。我的问题基本上是我将如何使用该数字来选择具有与“位置”相同数字的相应类对象?感谢您的任何建议。
答案 0 :(得分:2)
如果我理解正确,那么您想访问分配给父母子女的脚本组件。您可以使用GetComponent
方法:
for (int i = 0; i < Counties.transform.childCount; i++)
{
Transform t = Counties.transform.GetChild(i);
Current = t.name;
County county = t.GetComponent<County>();
//do something with county object...
}
如果没有组件,也可以先将组件添加到对象中:
for (int i = 0; i < Counties.transform.childCount; i++)
{
Transform t = Counties.transform.GetChild(i);
Current = t.name;
County county = t.GetComponent<County>();
if (county == null)
county = t.gameObject.AddComponent<County>();
//do something with county object...
county.name = t.name;
}
如果您正在寻找访问县的简便方法,也可以使用字典:
using System.Collections.Generic;
Dictionary<string, County> Counties = new Dictionary<string, County>();
//add County to dictionary
Counties.Add("NorthernIreland", new County(2630000, "NorthernIreland", "Connacht", "Munster", "Wales", 0));
//get County from dictionary
Counties["NorthernIreland"] //and do something with it...