Home > OS >  "Component" does not contain a definition for "enabled"
"Component" does not contain a definition for "enabled"

Time:02-26

Im trying to disable PlayerControllerScript by:

this.GetComponent("PlayerControllerScript").enabled = false;

But there is an error in title. What should I do?

CodePudding user response:

The method GetComponent(string type) is deprecated, which means that using it is not recommended, and you should look for another overload of the method.

One of the best way to do this is by using the method GetComponent<Type>(), where you directly put the type of your script in the place of Type instead of searching it through a string.

You should also consider to call only once GetComponent(), for example in the Start() method of your MonoBehaviour class, and save a reference to the script in a variable to avoid calling GetComponent() each time you need to do something with it, for performance reasons.

Something like that:

private PlayerControllerScript playerController;

private void Start()
{
    playerController = this.GetComponent<PlayerControllerScript>();

    playerController.enabled = false;
}

CodePudding user response:

GetComponent has multiple overloads:

  • public Component GetComponent(Type type);
  • public Component GetComponent(string type);
  • public T GetComponent<T>();

Component indeed doesn't have enabled. Only Behaviour (and subclasses) does since

Behaviours are Components that can be enabled or disabled.

Rather use the generic overload

GetComponent<PlayerControllerScript>().enabled = false;

which rather returns a PlayerControllerScript which most probably is a MonoBehaviour which then inherits Behaviour.enabled

alternatively you could also cast - but why go that way?

((PlayerControllerScript)GetComponent("PlayerControllerScript")).enabled = false;

As was mentioned in general it makes sense to cache references and if possible even avoid GetComponent completely like e.g.

// Already reference via the Inspector
[SerializeField] private PlayerControllerScript playerController;

private void Awake ()
{
    // or get ONCE as fallback
    if(! playerController) playerController = GetComponent<PlayerControllerScript>();

    playerController.enabled = false;
}
  • Related