- Home /
Convert small C# Code to JavaScript
Hi, i've tried to convert this c# script to javascript but i couldn't i'd be very happy if u helped me :)
this is the code
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DropList : MonoBehaviour
{
public class GuiListItem
{
public bool BigBool;
public string BigString;
public GuiListItem(bool myBool, string myString)
{
BigBool= myBool;
BigString= myString;
}
private List<GuiListItem> MyListOfStuff;
}
}
You should remove the spaces in the code to make it easier to read.
Answer by Berenger · Feb 15, 2012 at 08:05 PM
As I think you learn better when you do it yourself, I won't translate the code, but here are some rules :
you don't have the using ...; in javascript
javascript is by default a class inherited from Monobehaviour, you don't need to declare it. However, it's good to know that inheritance declaration is done with extends, not :.
variables declarations. Private by default in C#, they are public in javascript. they are declared that way : C# [access level] [scope (static, const, local)] [type] [name]; JS [access level][scope] var [name] : [type]. Note that this comes from my experience, that's probably not the name people give them.
to declare a function, begin with function and end with :[return type], if there is any.
Answer by aldonaletto · Feb 16, 2012 at 12:38 PM
This conversion isn't trivial, because uses List and class declaration. I didn't test this, but from other cases I think it should be written this way:
import System.Collections.Generic.List;
class GuiListItem {
var BigBool: boolean;
var BigString: String ;
function GuiListItem(myBool: boolean, myString: String){
BigBool= myBool;
BigString= myString;
}
}
// I suppose MyListOfStuff isn't part of the GuiListItem class, since it's a list
// of GuiListItem, thus I moved it out of the class declaration. If I'm right,
// declare and initialize this list in your code like this:
private var MyListOfStuff: List.<GuiListItem> = new List.<GuiListItem>;
As @Berenger said, in UnityScript you don't need the using lines and the script class declaration - the compiler adds them internally. Only System.Collections.Generic.List must be declared with import, because it's not automatically included.