- Home /
call function in javascript from c# script
How would I call a function in a js script attached to a GameObject from a c# script. the JSscript is attached to a GameObject named Cube. I'm trying to do this so far in the C# script but it's not working. I know how to do this from Js to Js but not C# to Js. Here's my non-working code attempt.
public GameObject go;
public JSscript myscript;
void Start(){
go=GameObject.Find("Sphere");
myscript=go.GetComponent<JSscript>();
}
right now it doesn't know what JSscript is.
The c# script is a plugin so it's already in the plugins folder. JS needs to be compiled first but plugins are compiled first. I can't use Send$$anonymous$$essage in this case. It's too slow. I tried changing the editor script order preference by the compiler still doesn't know what JSscript is. It says the type of namespace cannot be found.
If the c# file is already in the plugins folder, you're out of luck. C# and js can't call each other at the same level; one of them needs to be compiled first (by being in the plugins folder). Why can't you move the c# script into your assets folder?
If you can't move the c#, I wonder if you could have it call a different c# script that is in your assets folder, and then that one could call the js method. Worth a try.
I tried moving things around but the error never changes. Is there another way besides sendmessage to call a script. $$anonymous$$aybe something that wouldn't depend on the compilation order?
If you put your c# file directly in assets, and your js file in Assets/Plugins, it should work; I just successfully reproduced this on my machine.
Note that $$anonymous$$onoDevelop will give you errors if you try to build from there, but everything works perfectly in Unity.
Here's my code. $$anonymous$$yRegularFunc is in the javascript file "testjs.js", and it outputs to the log when it's called.
GameObject found = GameObject.Find ("Sphere");
if (found)
{
var foundScript = found.GetComponent<testjs>() as testjs;
if (foundScript)
{
foundScript.$$anonymous$$yRegularFunc();
}
else Debug.LogError("No attached testjs script.");
}
else Debug.LogError("No Sphere");
Answer by kmeboe · Oct 10, 2012 at 07:26 PM
This answer will tell you what you want to know: http://answers.unity3d.com/questions/267475/calling-javascript-method-fron-c-ngui.html
Summarizing: the javascript file would need to be compiled first (by putting it in one of the referenced directories). An alternative would be to use SendMessage().
Your answer
![](https://koobas.hobune.stream/wayback/20220613082146im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to use Android Dual Joysticks? 1 Answer
Space Craft controller. 1 Answer
call unity javascript from cs plugin 1 Answer
JavaScript 3 Arrays questions 1 Answer
JS file deleting multiple game objects 0 Answers