Removing element from array by value, not index

Hi,

I got an array. One of the elements inside this Array is “item_Key”. I would like to know how I can remove this item from the array. I am basically hitting a box, which will trigger to remove “item_Key” from the array. The only problem is I don’t know how to do this. I know I can remove an index with RemoveAt() but I am looking to remove by the value.

gameObject.Find("itemHolder").GetComponent("playerInventory").playerInventory.RemoveAt();

@Andreeeee

var RemoveItem : String;
RemoveItem = "item_Key";

var arr = gameObject.Find("itemHolder").GetComponent("playerInventory").playerInventory;

function OnTriggerEnter (other : Collider) {
    
}

var i = 0;

while (i < arr.Length && arr *!= RemoveItem)*

i++;

Well, you didn’t tell us what playerInventory is, but i guess it’s a List? The Remove function does exactly what you want :wink:

I can’t show you a full example since i don’t know what you actually store in your inventory. This example just uses an “Item” class. First you have to import the System.Collections.Generic namespace at the top of your script like this:

// Unityscript
import System.Collections.Generic;

// UnityScript
var playerInventory : List.<Item>;

To create an instance of a list you would do:

// UnityScript
playerInventory = new List.<Item>();

If you are using Unity’s Array class then you can use the [RemoveAt][1] function. This lets you remove an item by its integer index. You can find the index of the item with the key using a loop like this:-

  var i = 0;

  while (i < arr.Length && arr *!= key)*

i++;
If you are using a standard .NET array, you can use the following function:-
function RemoveByName(arr: String[], key: String) {
var i = 0;

while (i < arr.Length && arr != key)
i++;

if (i < arr.Length) {
for (var j = i + 1; j < arr.Length; j++) {
arr[j - 1] = arr[j];
}

System.Array.Resize.(arr, arr.Length - 1);
}
}
_*[1]: http://docs.unity3d.com/Documentation/ScriptReference/Array.RemoveAt.html*_