How do I cache GetComponent<Movement>(); in void start?

As Yotmew says in a few posts before me, I want to get into the habit to try to catch references in Void Start where I can, but Im not getting it to work. What word should I use when declaring the movementScript? Using Component right now, but that might be wrong.

Getting the error message: ‘Component’ does not contain a definition for ‘enabled’ and no accessible extension method ‘enabled’ accepting a first argument of type ‘Component’ could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS1061)

This is my code. Help would be great:).

6ae247e9606abd12fa83245185ab66ad 4617889f76d6ea92978260caccb752a8

1 Like

Hi Paula,

What exactly do you want to achieve? Disabling a specific component during runtime? If so, what you did, is almost correct.

When you assign your script to the Inspector in Unity, Unity creates a new object. And that object is also a Component object due to inheritence: Object > Component > Behaviour > MonoBehaviour > YourClass.

That’s why the Component type is not wrong. Your object is indeed also a Component object. However, when looking the Component class up in the API, you’ll notice that it does not contain any enabled property.

Due to the aforementioned inheritence, your object is also a MonoBehaviour object. MonoBehaviour contains an enabled property.

Ideally, you should use the actual type of your class, though, to be able to access “everything” within that class including the things that were inherited. It’s also better for the readability because MonoBehaviour is fairly nondescript, unlike EnemyMovement or Health or something like that.

Did this help?


See also:

1 Like

It did help a bit, though I don’t totally understand it yet^^. But I probably will learn more if I continue.
What kind of code should I use if I want to disable a script at runtime?
If Im asking too many questions, please let me know. I’m thankful for all your help!

That’s fairly easy. Maybe you could figure this out yourself, so I’m not telling you the solution right away unless you ask me to. Here is a hint, though:

Your script component inherits from a Unity class named MonoBehaviour. Look that class up in the Unity API and read the list with the things you can access. I already mentioned the relevant keyword, and if you click on it, you’ll find an example on the Unity website, which you could apply to your own code. Of course, you would not use the Image type in your script but the name of your class.

Please let me know if it worked.

This got bumped to the top so I’m gonna solve it.

Rather than:

Component movementScript;

You need to say:

Movement movementScript;

Cheers, Chris

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.