Unity:Component容器不可设置enabled成员属性的问题

问题现象

在Unity中,如果我们以public预设一个原生Component容器,用来存放通过反射找到的C#脚本,那么对这个容器设置enabled就会不成功:

        private Component TargetComponent;

        TargetComponent = AnimationCtrlEntity.GetComponent<MyAnimation>();

        TargetComponent.enabled = true;   // 编译错误

初学的同学可能会对此抱有违反直觉的感觉。“我们激活/失活一个脚本,不是很正常的行为吗?” 

探索一番,我们自定义了一个名为 MyAnimation 的类,继承了 MonoBehaviour:

        AnimationCtrlEntity.GetComponent<MyAnimation>().enabled = true;

        这段代码就可以执行

why?

解决方法

这个问题的直接原因,是因为Component容器默认不含有 enabled 成员属性

改成以下就可以:

方法一:

        private MyAnimation TargetComponent;

        TargetComponent.enabled = true;   // 编译正常

方法二(编译能过,但不推荐的写法):

        private Component TargetComponent;       

        TargetComponent = AnimationCtrlEntity.GetComponent<MyAnimation>() ;

        (TargetComponent as MyAnimation).enabled = true;   // 编译正常

总结

本质原因是我们自定义的类型 MyAnimation 继承了 MonoBehaviour 类,而 MonoBehaviour 的上一级 Behaviour 类中,包含了这个 enabled 成员属性。而 Component型容器 虽然能接收不同类型的脚本,但他的父类是 UnityEngine.Object,这使得二者不具备相同的基类属性和方法,自然也无法从中访问到 “不存在的 enabled 成员属性”。

猜你喜欢

转载自blog.csdn.net/qingxiu3733/article/details/131878686
今日推荐