Rewriting C# to JavaScript

Hey! I’m rewriting a C# script to JavaScript, so I can better understand it, because I’m bad at C#. I ran into few problems. First. Where to place the variables, that are declared between functions? Than this.

    public WorldData WorldData
    {
        get { return m_WorldData; }
    }

It’s at the start, at declaring. How can I write it in JS?

– David

You can actually do properties in js. The syntax is funny, but doable. First you need to explicitly declare the class, then the getter:

public class MyClass extends MonoBehaviour {
    private var myVar : int = 3;

    function get MyVar : int { 
         return myVar;
    }
    function set MyVar (value : int) {
        myVar = value;
    }
}

then it is accessible as

myInstance.MyVar

While the syntax looks really strange to any C# dev, I do like the fact that there’s a function in there to remind you properties are methods.

BTW, info taken from this question.

That particular piece of code is a getter for a Property called WorldData. Properties are a C# language feature, they’re not available in JS. Your only option in JS that doesn’t break other scripts that might reference WorldData is to create a public variable called WorldData instead.

By the way, your question title needs to be reversed. You’re asking about C# to JS. :wink: