有几种不同的方法可以做到这一点。
-
如果它们都在同一个父对象下,没有其他对象,则可以循环通过子对象并更改它们的颜色
GameObject Parent = GameObject.Find("ParentObject");
for( int x = 0; x > Parent.transform.childCount; x++);
{
Parent.transform.GetChild(x).GetComponent<Renderer>().material.color = Color.red;
}
-
如果少于20ish,您可以创建一个列表,并在将列表的大小更改为您拥有的对象数量后,将每个变换拖放到检查器中。
/*Make sure you have Using "System.Collections.Generic" at the top */
//put this outside function so that the inspector can see it
public List<Transform> Objs;
// in your function put this (when changing the color)
foreach(Transform Tform in Objs){
Tform.GetComponent<Renderer>().material.color = Color.red;
}
-
类似于2,如果你想在代码中完成这一切,你可以做
//Outside function
public List<Transform> Objs;
//inside function
Objs.Add(GameObject.Find("FirstObject").transform);
Objs.Add(GameObject.Find("SecondObject").transform);
//... keep doing this
//now do the same foreach loop as in 2
-
你可以通过标签进行搜索(如果你有很多对象)(我想这会花费更长的时间,因为它会通过每个组件,但我没有证据支持这一点)
//Outside function
public GameObject[] Objs;
//inside function
Objs = GameObject.FindGameObjectsWithTag("ATagToChangeColor");
foreach(Transform Tform in Objs){
Tform.GetComponent<Renderer>().material.color = Color.red();
}
关于这个评论:
//If I change these variables to -GameObject-
//It blocks me to access the renderer
//Making the variables public doesn't work either
如果您将其设置为GameObject类型,则只需执行以下操作即可轻松访问渲染器:
public GameObject cube;
public void Start(){
cube.GetComponent<Renderer>().material.color = Color.red();
}
并且将变量公开允许unity的检查员查看变量,以便您可以在unity编辑器中更改它们,而无需打开脚本。