- Home /
Can't use remove with string[] ?
I try to remove the duplicate names of the array using the for loop, but this is getting an error. I don't know why?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ListManager : MonoBehaviour {
public string[] ListOfItems;
public int[] AmountOfItems;
private int ItemAmount;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
ItemAmount = SpawnItem.main.dropItem.Count;
ListOfItems = new string[ItemAmount];
for(int i = 0; i < SpawnItem.main.dropItem.Count; i++){
ListOfItems[i] = SpawnItem.main.dropItem[i].Name;
for(int x = 0; x < SpawnItem.main.dropItem.Count; x++){
if(ListOfItems[i] == ListOfItems[x]){
ListOfItems.Remove(x);
}
}
}
AmountOfItems = new int[ItemAmount];
for(int i = 0; i < SpawnItem.main.dropItem.Count; i++){
AmountOfItems[i] = SpawnItem.main.dropItem[i].ItemID;
}
}
}
The error says !
ListManager.cs(26,53): error CS1061: Type `string[]' does not contain a definition for `Remove' and no extension method `Remove' of type `string[]' could be found (are you missing a using directive or an assembly reference?)
Please Help :3
Answer by Joyrider · Aug 14, 2013 at 10:34 AM
Remove only works with Lists, you created an array.
a list is declared like this:
List<string> ListOfItems = new List<string>(ItemAmount);
afterwards you can use .Add or .Remove
And there is something wrong with your two for-loops. You're iterating through the whole array, even though it is not fully populated yet.
e.g. the first time you go through your loops, you only have the first entry that is assigned, all the rest is empty; and still you're comparing to all the entries. Wasting quite a bit of energy.
No, an array is fixed size. You can't reduce the number of slots. And can't just remove a slot at an arbitrary position.
That is what List are for ;)