您的位置:首页 > 移动开发 > Unity3D

在Unity中,获得包含某种component的gameobject

2015-11-12 15:20 459 查看
游戏开发的过程中可能有时想要去找所有包含某种component的gameobject。Unity似乎没有提供这样的接口。但是通过下面几个步骤是可以实现这种操作的,这里介绍在场景中所有包含Animation这种component的游戏对象。关键接口是GameObject.FindObjectsOfType<T>();
1.首先找到所有的这些组建
2.通过这些组建的gameObject返回包含这些组建的游戏对象。具体代码如下:


public static GameObject [] FindAllHeroModels()
{

//1.find the hero's animation component
object [] heroAnimations = GameObject.FindObjectsOfType<Animation>();
//assigned the array of hero's model
GameObject[] HeroModels = new GameObject[heroAnimations.Length];
//test
for (int i = 0; i < heroAnimations.Length; i++)
{
if (heroAnimations[i] is Animation)//check the type
{
HeroModels[i] = (heroAnimations[i] as Animation).gameObject;
}
else
{
Debug.Log("Can't find the game object FUNC:FindAllHeroModels POS:AnimationController.cs");
return null;
}

}

return HeroModels;
}


通过上面的代码,我们可以找到所有包含Animation的游戏对象,并且分配到HeroModels这个数组中,接下来你就可以通过这个数组然后,对模型进行各种操作了,比如说播放动画。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: