Hi
I want to access a variable in a Java Script from a C Sharp Script. I know a little bit about the Java Script in Unity, but I´m very stupid about C Sharp Script. So I know that I have to make a static var in Java Script, but I don´t know how to access the variable in C Sharp Script.
Thanks for all replys.
I know the Unity documentation makes static vars sound like the way to go, and sometimes they are, but don’t be mislead, most of the time you will want to use get component. Static vars are created as only one instance of a variable. So, let’s say you have a bunch of enemies. If you attack one of them and they have a “static var health = 10”. If you hurt the enemy for 6 points or something, every enemy will lose those 6 points. It acts in simple terms, like a voodoo doll. Whatever you do to one, you do to all of them.
In most cases, you want to use GetComponent then access the variable that way, then you don’t have to create a static var, only a public variable (in some cases you could use protected) so you can have each object affected individually.
Now, to access a js script from a c# script, first you have to place your js script in a folder that gets compiled earlier such as standard assets and place the c# script outside of any folder. Make sure the js variable is public (it is by default), then use the following code to cache a link to it.
public MyJSScript script;
void Start () {
script = GetComponent("MyJSScript"); //you have to use a string here.
}
void Update () {
//to change any variable go:
script.var = someValue;
}
PS. I think C# variables are protected by default. Please correct me though if I’m wrong.
But in this case I need to have a static Variable.
I have this java script
static var test : float;
function Update () {
}
and this in c#
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public javatest.test;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
and I get this message
Assets/test.cs(5,29): error CS8025: Parsing error
(This is a great forum! Thanks for having the time to help somebody how seems to be realy stupid like me )
The name `javatest’ does not exist in the current context
Any ideas ??
In the Unity Script Reference it says :
Global variables
You can also create global variables using the static keyword.
This creates a global variable called someGlobal.
// The static variable in a script named ‘TheScriptName.js’
static var someGlobal = 5;
// You can access it from inside the script like normal variables:
print(someGlobal);
someGlobal = 1;
To access it from another script you need to use the name of the script followed by a dot and the global variable name.
print(TheScriptName.someGlobal);
TheScriptName.someGlobal = 10;