|
I have a static variable inside a JavaScript script. How can I access it from inside a C# script?
(comments are locked)
|
|
UnityScript files get compiled to classes underneath just like C# files. You can access a static field the same way as C# class. For unity script the class name is the file name so it should be Edit: Here is an example of how this works. ACSharpScript.cs goes in some folder I define to ensure it's compiled last:
...then, in Standard Assets I create a UnityScript file called AUnityScript.js :
the C# is incrementing the static COUNTER field in the UnityScript class and an instance of the UnityScript (the instance created when you hang it on the graph) is reading the static field every frame. Hang these on the scene and try it... you will see COUNTER incrementing every frame. Thanks Ray but could you be more specific? I mean, I have a static var myStaticVar: int in a UnityScript (named MyJSScript). Under certain conditions, I want a c# script to increase myStaticVar by one. Writing (in the C# script): MyJSScript.myStaticVar +=1; doesn't work. What is the correct syntax?
Apr 03 '11 at 08:22 PM
schwertfisch
Doesn't compile or doesn't work? That looks right to me. You can access C# fields from unity script and unity script fields from C#. The important thing is the compile order described in the link. If one language is to call another in another language the target class must be compiled before the caller.
Apr 03 '11 at 08:33 PM
raypendergraph
At first, I had both scripts (UnityScript and C#) inside a folder named "Scripts" and I was getting the error: error CS0103: The name 'MyJSScript' does not exist in the current context. After that, I moved the UnityScript inside the Plugins folder (so that it's compiled first). This way I got rid of the error, but what I am telling the c# script to do (MyJSScript.myStaticVar +=1) simply doesn't happen.
Apr 03 '11 at 08:41 PM
schwertfisch
May be something else going on... we do this with a few UnityScript components that we did not write. Our code base is C# too. If you are making it past the compilation you should be OK with this. Maybe try a different test case or something like setting the the thing to 20 and reading it from C#.
Apr 03 '11 at 09:04 PM
raypendergraph
@schwertfisch - I updated the post with a simple example.
Apr 04 '11 at 12:07 PM
raypendergraph
(comments are locked)
|
