I have a piece of code done in a c# file, this file is called unit.cs, and inside it a variable is declared, variable name “options”.
I want to access this variable from a js script file.
In this small example, the variable object has a gameObject that has unit.cs attached to it.
So, I’m doing this :
var object : GameObject;
var inf = object.GetComponent(“unit”);
var inf2 = inf.options;
Unity is giving me this :
BCE0019: ‘options’ is not a member of ‘UnityEngine.Component’.
Anyone knows what the problem is ?
I have no issues doing this same thing between two JS scripts, but each time I try to do the same thing between JS and C# I get this kind of problems.
Using strings with GetComponent makes it return Component instead of the type, so avoid using strings wherever possible. Otherwise you have to cast it.
The string version of GetComponent is the javascript-y way of doing things. It’s useful on a few cases, but you usually want to use the generic version, which will return you the component as its proper data type.
If you have a Unit class that extends MonoBehaviour, you can get it like this:
Unit myUnit = object.GetComponent();
No need to type-cast if you do it like that, and it’s generally a lot nicer to work with.
Also, don’t use var to hold references to things you know the data type of. If you have a GameObject reference (like ‘object’), use GameObject object; In C#, var is meant to be used when you don’t know what data type to expect from something, and in most cases, you do.
Use the generic version of GetComponent in JS to get the type, otherwise as Eric stated it will be of type Component. The case of the class name might be different, adjust where needed.
var inf : Unit = object.GetComponent.<Unit>();
var inf2 = inf.options;
No, you should actually not use the generic version of GetComponent in JS. It’s slightly slower and uglier than just using the normal version, and doesn’t do anything that the normal version doesn’t do. What I said was to not use strings.
Right:
var inf = GetComponent(Unit); // inf is statically typed as Unit
Wrong:
var inf = GetComponent("Unit"); // inf is Component...don't do this