- Home /
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
Answer by CHPedersen · Jul 11, 2011 at 10:26 AM
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. ;)
Thanks, and what about if (Physics.Raycast(ray, out hit, 4.0f)) ? what is the OUT?
As far as I know you can use it without the "out".It is only needed in C#
The "out" keyword specifies that the parameter, hit, is passed by reference to Physics.Raycast, and that it is the responsibility of Physics.Raycast to set the variable in its definition. Another method that uses this keyword in .Net is the TryParse-method of float, int and double.
See the documention on Physics.Raycast for JavaScript usage: http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html
Answer by Peter G · Jul 11, 2011 at 12:39 PM
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.
Didn't knew that it's possible in US. I don't use JS but i would always use properties. Changing a property into a public variable is a design break. Of course is you recompile all related code it will work, but only in this special case. If you do other things in the getter / setter it can't be done with a public var ;) Just think of a singleton instance.
+1
Thanks.. But I managed to not rewrite it, because it was time consu$$anonymous$$g, and i can read C# so maybe another time... And it's really good that there is get/set in JavaScript :).
$$anonymous$$+!
Your answer
Follow this Question
Related Questions
Which variable can be implicitly declared? 1 Answer
GameObject.Find either can't be called or is in the wrong scope. 0 Answers
javascript: declaring a variable in 'while' loop 2 Answers
best place to declare variables in the script 2 Answers
Problem when trying to save variable in another variable. 1 Answer