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

游戏开发的过程中可能有时想要去找所有包含某种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这个数组中,接下来你就可以通过这个数组然后,对模型进行各种操作了,比如说播放动画。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值