- Home /
Change static variable in JS through Csharp
Hi. I am working on a script to change a variable of a JS script through a C#
my JS:
static var counter : int = 10 + counter2;
static var counter2 : int = PlayerPrefs.GetInt("CubeCoin");
function Update(){
CubeCoin.counter = 10 + counter2;
if(CubeCoin.counter2>=0){
CubeCoin.counter2=0;
}
}
my C#
using UnityEngine;
using System.Collections;
public class CSharp2 : MonoBehaviour
{
//create a variable to access the JavaScript script
static CubeCoin jsScript;
void Awake()
{
//Get the JavaScript component
jsScript = this.GetComponent<CubeCoin>();
}
void OnGUI()
{
if (GUI.Button (new Rect (15, Screen.height-Screen.height/5, Screen.width/6, Screen.height/13), "bla")) {
jsScript.counter2 +=1;
}
}
}
but this don`t work. i got error CS0176 Static member CubeCoin.counter2 cannot be accessed with an instance reference, qualify it with a type name instead. how can i fix that ? and i have to leave the variable static.
Answer by Graham-Dunnett · Sep 04, 2014 at 05:35 PM
A static member belongs to the class itself, and not to a particular object that has that type. So, it's incorrect to try an access a particular instance of that class through GetComponent()
. Instead, you need to use the class:
// replacement for line 19
CubeCoin.counter2 += 1;
If you are not familiar with static
members, take a look at the GameObject
class:
http://docs.unity3d.com/ScriptReference/GameObject.html
Lots of the variables apply to regular game objects in your scene. Near the bottom of the page is a section titled "Static Functions". This section describes the static
functions of the GameObject
class. If you look at the documentation for the Find()
function you'll see that you use GameObject.Find()
- that's to say you use the class name and not a variable set to a particular game object.