I have two scripts each on a different objects; one is on enemy character other is on a player that i control. General structure of scripts on both characters is almost the same.
What I want to do is turn off a particular script with other script, both of which are on a same character so I do this:
var navMshPlayer = gameObject.GetComponent("NavMshPlayer");
navMshPlayer.enabled = false;
and it works
Now I go to enemy character and i try to do the same thing
var navMeshEn = gameObject.GetComponent("NavMshEnemy");
navMeshEn.enabled = false;
and it does not work! It returns an error “BCE0019: ‘enabled’ is not a member of ‘UnityEngine.Component’.”
After searching forums for a sollution I came with an idea to try this:
var navMeshEn = gameObject.GetComponent(NavMshEnemy);
navMeshEn.enabled = false;
And it worked!
Can someone explain to me why sometimes I have to access a script like this:
var navMeshEn = gameObject.GetComponent("NavMshEnemy");
and sometimes like this:
var navMeshEn = gameObject.GetComponent(NavMshEnemy);
I went throught all my scripts and all unity documentation for an answer to this question.
What is the logic behind it? Is it a bug?
There’s no bug; as described in the docs, using GetComponent with strings returns Component rather than the actual type. You should almost never use GetComponent with strings. The docs tell you the one case where you would (“for example when trying to access a C# script from Javascript”), but mixing languages in game scripts is also something you should avoid. Mixing languages is fine if you have utility scripts which are one-way, but when you start trying to interconnect game logic with GetComponent, that should all be one language.
var navMshPlayer : NavMshPlayer = gameObject.GetComponent(NavMshPlayer) as NavMshPlayer;
Does not work. Errors:
Assets/Standard Assets/1MyFolder/Istats.js(36,36): BCE0018: The name ‘NavMshPlayer’ does not denote a valid type (‘not found’). Did you mean ‘UnityEditor.NavMeshBuilder’? Assets/Standard Assets/1MyFolder/Istats.js(36,92): BCE0018: The name ‘NavMshPlayer’ does not denote a valid type (‘not found’). Did you mean ‘UnityEditor.NavMeshBuilder’?
Well…in JS, GetComponent(Type) always returns Type; there’s no need to specify Type repeatedly like that and it won’t solve any problems. If you ever do GetComponent(Type) and get an error, it’s because Type doesn’t exist in that context. This is caused by mixing languages, or by mixing compiler stages caused by Magic Folders. i.e., a script in Standard Assets can’t see scripts outside because it’s compiled first. (Or it’s caused by Type not actually existing anywhere…)
Update: Ive just noticed that this script is in Standart Assets folder which compiles differently AFAIK. Ive moved it where other scripts are and this works now:
var navMshPlayer : NavMshPlayer = gameObject.GetComponent(NavMshPlayer) as NavMshPlayer;
Eric5h5, thx. In the past ive mixed C# with JS thats why Ive used Standard Assets folder.