Unity: Component container cannot set enabled member attributes

Problem phenomenon

In Unity, if we preset a native Component container as public to store C# scripts found through reflection, then setting enabled on this container will fail:

        private Component TargetComponent;

        TargetComponent = AnimationCtrlEntity.GetComponent<MyAnimation>();

        TargetComponent.enabled = true; // Compilation error

Beginners may find this counterintuitive. "Isn't it normal behavior for us to activate/deactivate a script?" 

After some exploration, we customized a class named MyAnimation and inherited MonoBehaviour:

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

        This code can be executed

why?

Solution

The direct cause of this problem is that the Component container does not contain enabled member attributes by default .

Just change it to the following:

method one:

        private MyAnimation TargetComponent;

        TargetComponent.enabled = true; // Compiled normally

Method 2 (compilation can pass, but writing is not recommended):

        private Component TargetComponent;       

        TargetComponent = AnimationCtrlEntity.GetComponent<MyAnimation>() ;

        (TargetComponent as MyAnimation).enabled = true; // Compiled normally

Summarize

The essential reason is that our custom type MyAnimation  inherits the MonoBehaviour class, and the upper-level Behavior class of MonoBehaviour contains this enabled member attribute. Although the Component container can receive different types of scripts, its parent class is UnityEngine.Object, which means that the two do not have the same base class properties and methods, and naturally cannot access "non-existent enabled member properties" from them. . 

Guess you like

Origin blog.csdn.net/qingxiu3733/article/details/131878686