- Home /
Accessing global variable from java in c#
I believe there is similar question in the forum, but I just can't find it, sorry.
My question is how do I access a global variable from a java script in a c# script.
For instance, I have a global variable called "world" defined in a java script called "A". Then how do i access this variable in a c# script. I guess it need to be declared in c# again?
Thanks in advance!
Answer by aldonaletto · May 14, 2012 at 01:33 PM
Javascript and C# can't see each other at compile time, but scripts already compiled become pure CIL code and are visible to other scripts independently of language.
Unity compiles scripts in 3 consecutive waves, according to the folder they are: Standard Assets and Plugins first, Editor subfolders next, then other folders. You can place the JS script in Standard Assets or Plugins, and the C# one in some other Assets subfolder.
If you only need to access global variables (static?), place all of them in a script and save it in Standard Assets, and place all other scripts in a custom folder in Assets (Assets/Scripts, for instance).
wow I didn't know that, thanks for your helpful information!
Answer by bompi88 · May 14, 2012 at 01:36 PM
If both scripts are one the same GameObject, you can do something like this. And you should put your A.js in a folder called "Plugins", because C# is built before JS. You can read more about Script compilation here. This is non-static method of doing it. Edited to needs: two seperate GameObjects.
// A.js
public var hello : String = "This is a string";
//B.cs
using UnityEngine;
using System.Collections;
public class B : MonoBehaviour {
public GameObject go;
private A Ascript;
void Start () {
Ascript = go.GetComponent<A>();
Debug.Log(Ascript.hello);
}
}
They are not on the same GameObject, but I will try it out myself when I'm home, thanks for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220613071451im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Global Scripts/Variables 1 Answer
Camera following a moving object 0 Answers
Initiating the playback of a toggle through another onClick button 0 Answers
My scoring system doesn't work 2 Answers
How to make a global settings Editor Window for my game 0 Answers