Explanation on how to use LIST<> in UnityScript

Hi,

I’m on a mission to find the index number in a List<> of a transform by it’s name.

I was previously using Arrays but I have been pointed in the direction of Lists. From what I can tell they are like Arrays but with lots of cool built in functions. There is a tiny performance hit from what I can tell, but apparently nothing to worry about in smaller projects. Here is an excellent reason why to use Lists instead of Array:

So they sound great but I’m having problems getting to grips with it. So far I have found out how to get the name of an item from it’s index array. But I can’t get it to work the other way around, and give me the index number by searching the name of the item in the list. Here is an example of my code so far:

import System.Collections.Generic;

var attackerList = new List.< Transform>()
//attackerList list populate here

function Start () {
var thisItem = attackerList[2];
print ("Attacker name is=" + thisItem);
}

So does anyone know of any good guides out there? And any suggestions on how to jump the final hurdle :wink:

Thanks!

Paul

Use List.FindIndex:

import System.Collections.Generic;

var attackerList : List.< Transform>;

function Start () {
    var index = attackerList.FindIndex (function (tr : Transform) tr.name == "TransformNameHere");
    Debug.Log (index);
}

I use a basic loop in something I am working on to add an ability by its index on a master list by using the below:

function AddAbility(skill : Ability){
	var abilityIndex = GetAbilityIndex(skill, masterAbilityList);
	if (abilityIndex != -1){
		AddAbility(abilityIndex); //This calls an AddAbility (int) method in case you were wondering
	}
}



function GetAbilityIndex(theItem : Ability, theList : AbilityList){
	for (var i = 0; i < theList.abilities.length; i++){
		if (theList.abilities *== theItem){*
  •  	Debug.Log("Item is at #" + i);*
    
  •  	return i;*
    
  •  }*
    
  • }*
  • Debug.Log(“Error Ability Index!”);*
  • return -1;*
    }
    So I would assume for you, something like:
  • for (var i = 0; i < attackerList.length; i++){*
    _ if (attackerList == transform){ //Current script transform – can replace with other values if needed_
    * Debug.Log(“Item is at #” + i);*
    * return i; // returns the index of the transform*
    * }*