Search code examples
javascriptunity-game-engineunityscript

Why is a global variable (inside function) not identified?


So, I was trying to initialize variables and put a few global variables in my Unity script, but when I run the code, it says that x, y, and z are unknown identifiers. I've been trying to find the answer to this:

function Awake () {
    x = 0; //Unity doesn't work with commas 
    y = 0;
    z = 0;
}

function Update () {
    if (Input.GetTouch) {
        x = x-1;
    }
    Transform.position = Vector3(x,y,z);
}

The thing with putting the variables outside the function is that they will repeat and act as update.

I'm also new to Unity, and JavaScript.


Solution

  • It looks to me (granted with my limited exposure to unity) like you need to declare your variables at a global level. Try doing something like this:

    // declare these variables in the global scope.
    var x;
    var y;
    var z;
    
    function Awake () {
        x = 0;
        y = 0;
        z = 0;
    }
    
    function Update () {
        if (Input.GetTouch) {
            x = x-1;
        }
        Transform.position = Vector3(x,y,z);
    }