当我有多个子对象时,如何从.GetComponentInChildren
中选择要从哪个子组件中获取组件?
使用此代码,我只得到第一个孩子的MeshRenderer
。
selectedObj.GetComponentInChildren<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
答案 0 :(得分:2)
GetChild
无法做到这一点。您可以在int CHILD_INDEX = 3;
selectedObj.transform.GetChild(CHILD_INDEX).GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
函数的帮助下使用子GameObject的索引执行此操作。下面的代码将获得索引为3的子GameObject的组件。
GetComponentInChildren
为此创建自定义通用扩展方法,并将index参数添加到public static class ExtensionFunction
{
public static T GetComponentInChildren<T>(this GameObject gameObject, int index)
{
return gameObject.transform.GetChild(index).GetComponent<T>();
}
}
函数:
int CHILD_INDEX = 3;
selectedObj.GetComponentInChildren<MeshRenderer>(CHILD_INDEX).material.SetColor("_EmissionColor", Color.red);
然后你现在可以做:
FindChild
每次只想从儿童GameObject获取组件时使用scheduler caught exception:
JIRA::HTTPError
/Users/users/.rvm/gems/ruby-2.2.4/gems/jira-ruby-1.1.3/lib/jira/request_client.rb:16:in `request'
/Users/users/.rvm/gems/ruby-2.2.4/gems/jira-ruby-1.1.3/lib/jira/client.rb:213:in `request'
/Users/users/.rvm/gems/ruby-2.2.4/gems/jira-ruby-1.1.3/lib/jira/client.rb:191:in `get'
/Users/users/.rvm/gems/ruby-2.2.4/gems/jira-ruby-1.1.3/lib/jira/resource/issue.rb:64:in `jql'
/Users/users/.rvm/gems/ruby-2.2.4/gems/jira-ruby-1.1.3/lib/jira/base_factory.rb:33:in `block (2 levels) in delegate_to_target_class'
/Users/users/../../jobs/jira_number_of_issues_in_filter.rb:35:in `block (2 levels) in <top (required)>'
/Users/users/.rvm/gems/ruby-2.2.4/gems/rufus-scheduler-2.0.24/lib/rufus/sc/jobs.rb:230:in `call'
/Users/users/.rvm/gems/ruby-2.2.4/gems/rufus-scheduler-2.0.24/lib/rufus/sc/jobs.rb:230:in `trigger_block'
/Users/users/.rvm/gems/ruby-2.2.4/gems/rufus-scheduler-2.0.24/lib/rufus/sc/jobs.rb:204:in `block in trigger'
/Users/users/.rvm/gems/ruby-2.2.4/gems/rufus-scheduler-2.0.24/lib/rufus/sc/scheduler.rb:430:in `call'
/Users/users/.rvm/gems/ruby-2.2.4/gems/rufus-scheduler-2.0.24/lib/rufus/sc/scheduler.rb:430:in `block in trigger_job'
只会减慢你的游戏速度,特别是如果你做了很多。
答案 1 :(得分:1)
如果您知道具有所使用组件的子对象的唯一名称,则可以使用transform.FindChild("nameOfChildObject")
查找要查找的特定子对象。所以在你的情况下你可以说:
selectedObject.transform.FindChild("nameOfChildObject").GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
答案 2 :(得分:0)
这对我有用:
MeshRenderer[] var = selectedObj.GetComponentsInChildren<MeshRenderer>;
foreach (material m in var)
{
m.SetColor("_EmissionColor", Color.red);
}
然后我只是循环 var 来修改每个对象。