How to use generics in unity javascript

This is some code based on http://unity3d.com/support/documentation/Manual/MonoUpgradeDetails.html and List<T>.Capacity Property (System.Collections.Generic) | Microsoft Learn
It showcases the use of generics in unity js.

import System.Collections.Generic;

function Start ()
{
    var list : List.<String>;
    list = new List.<String>();
    //Capacity is the number of elements that the List<T> can store before resizing is required
    //Count is the number of elements that are actually in the List<T>.
    Debug.Log("list capacity is " +list.Capacity);
    Debug.Log("list count is " +list.Count);
    Debug.Log("Adding 4 entries");
    
    list.Add("Generics");
    list.Add(" work");
    list.Add(" in");
    list.Add(" js");
    list.Add(" too.");
    
    Debug.Log("Note that now capacity is bigger than count"); 
  
    Debug.Log("list capacity is " +list.Capacity);
    Debug.Log("list count is " +list.Count);
    
    //js cannot have foreach but can use for in
    var sentence:String;

    for( var word:String in list)
    {
        sentence +=word;
    }
    Debug.Log(sentence);
    Debug.Log("list.Contains(\"generics\") is " + list.Contains("generics"));
    Debug.Log("list.Insert(5, \" Unity js rocks !\");" +" inserts a new item at the end of the list");
    list.Insert(5, " Unity js rocks !");
    Debug.Log("Let's check it");
    sentence = "";
    
    for( var word:String in list)
    {
       sentence +=word;
    }
    //For more methods of List check out http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
    //Or google c sharp List
   

}
2 Likes

Thanks for this it is very helpful

    list.Add("Generics");
    list.Add(" created");
    list.Add(" in");
    list.Add(" C#");
    list.Add(" etc.");
    list.Add(" can");
    list.Add(" be");
    list.Add(" accessed");
    list.Add(" by");
    list.Add(" js");
    list.Add(" (us)");
    list.Add(" too.");

FTFY

You didn’t “fix” anything though.

–Eric

Not relevant with the topic specifically, but can anyone tell me why i should use java script rather than c# ?
Does it make a difference on mobile platforms or something?

By and large it’s personal preference.

Really, please don’t start that up here, it’s been discussed to death and back.

–Eric

Hi,

obliviux : If you also feel like sharing some bits of code that demonstrate how to use .NET features in unityscript ( or js ), please do so, we all need as much help as possible.

NPSF3000 :

Eric5h5: FTFY has a double meaning… ( Those evil C# coders again )…

Aubergine : Indeed, it is more about personal preference IMHO too.

thanks for this. It really helped me with getting WatchVar in DebugConsole work Unity3D: Heavily modified version of Jeremy Hollingsworth's DebugConsole script. · GitHub

Hi,
Looks really useful, thanks for sharing.