Search code examples
functionclassunity-game-engineunityscript

Unity3d Use top level variable in class


I have a problem with using a variable that I declared outside the class, in a class. If I try this, Unity acts as if the variable doesn't exist.

#pragma strict
var chunkWidth=49;
class Chunk{
    var width:short;
    var position:Vector3;
    function Chunk(pos:Vector3){
        this.width=chunkWidth; //this gives the error: Unknown identifier: 'chunkWidth'.
        this.position=pos;
    }
}

This error also occurs when I want to use a function within the class.


Solution

  • You can change a variable in the inspector view if the variable is made public. Put the variable inside the class and make it a public variable. Then go to Unity and click the object that has this component attached. You can then change the variable in before you hit play. The variable will save in unity, but not in your code. So if you use this code with another object the variable will need to be set again in the inspector. But once set Unity will save that value within your project.