- Home /
Referencing a c# component script from JS script
How do you reference a c# component script from a JS script? Do you need to store the reference as you would with a JS component, to prevent having to fetch GetComponent each time?
Trying the usual below for a c# script named CSharpComp.cs, I get this error: 'CSharpComp' does not denote a valid type ('not found').
myfile.js contains:
var csharpcomponent:CSharpComp;
function Start(){
csharpcomponent = GameObject.Find("MainObj").GetComponent(CSharpComp);
}
Answer by aldonaletto · Jan 21, 2012 at 04:56 PM
C# and JS can't see each other at compile time (different compilers are used for each language), but already compiled scripts can be seen by any language. If you place the C# script in Plugins or StandardAssets, and the JS script in another Assets folder (Assets/Scripts, for instance), the C# script will be compiled in the "first wave", thus the JS script will know it and compile ok (see Script Compilation). NOTE: this is a one way via: the CS script won't be able to see the scripts not yet compiled (JS or C#).
If you just need to call some CSharpComp function, SendMessage("FunctionName", argument) can be used. This is a very limited alternative, since SendMessage accepts only a single parameter, but it works independently of language or compilation order (it's a runtime feature).
Also, I read Send$$anonymous$$essage should be used sparingly since it is very slow and impacts performance
It looks like this does not work exactly, as $$anonymous$$ainObj contains the CSharpComp.cs that myfile.js is trying to refernece... the GetComponent does not work!
It's weird! I tested a JS script in Assets/Scripts and it found $$anonymous$$ouseLook.cs without any problem ($$anonymous$$ouseLook.cs is stored in Standard Assets/Character Controllers/Sources/Scripts).
And you're right about Send$$anonymous$$essage: it must check all scripts and look for the specific function in each one, thus using Send$$anonymous$$essage frequently isn't a good idea.
Answer by Kryptos · Jan 21, 2012 at 07:32 PM
You can set the assembly dependencies in the MonoDevelop project. Right click on the 'References' folder under the Assembly-UnityScript project and 'Edit Preferences'.
Again, cyclic references are not allowed so you can't make both projects see each other.
Anyway, this is bad practice to have a project with both JS and C#. You should consider translating all scripts to one unique language.