Enabling / Disabling C# Scripts - Why am I getting the error "not a member of 'UnityEngine.Component'"?


I'm having a problem with disabling scripts with JavaScript.

Usually this works:

var code : SampleCode = GetComponent(SampleCode);
code.enabled = false;

This seems to only work on javascript. When I try this on c# scripts it says that SampleCode is not a valid type.

Any ideas? I've tried the GetComponent("SampleCode").enabled = false; method but it doesn't work either - it gives the error - BCE0019: 'enabled' is not a member of 'UnityEngine.Component'.


Christian Stewart

Eric5h5's comment is important about compilation order, if you're trying to disable a c# script from a Javascript script.

However it possibly sounds as though you're trying to re-write this in C#. If this is the case, the problem is happening because "GetComponent" returns a type of "Component" (which Javascript automatically casts to the correct type for you, but c# does not). In C#, you need to do either this:

SampleCode code = (SampleCode) GetComponent(typeof(SampleCode));

or use the newer generic version:

SampleCode code = GetComponent<SampleCode>();

Then you'll be able to use:

code.enabled = false;

You have to get C# scripts to compile earlier so Javascript knows about them. See the docs: http://unity3d.com/support/documentation/ScriptReference/index.Script_compilation_28Advanced29.html