- Home /
RemoveAt(T[]codes, T code) doesnt work
im using RemoveAt to remove a string from an array. im using somthing like...
using UnityEngine;
using System.Collections;
using System;
public class network : MonoBehaviour {
public string[] Codes;
public string myCode;
public bool removeCode;
void Update(){
if(removeCode){
RemoveAt(Codes, FindIndex(Codes, myCode));
}
}
public int FindIndex<T>(T[]codes, T code){
return Array.IndexOf(codes, code);
}
void RemoveAt<T>(T[]codes, int index){
removeCode = false;
}
}
Im not sure what to put in RemoveAt to remove the string from the Array, but it doesnt work as it is.
Comment
Best Answer
Answer by Lunatix · Dec 08, 2014 at 04:45 PM
You can't actually "remove" something from an array - you can set it to "null" but this will leave an empty space inside the array.
If holding a null value inside your array is okay, just use codes[index] = null;
. If you want to remove the entire slot, you can:
A) Create a new array with everything before and behind the specified index, which will work fine but you end up moving a lot of data around and allocating new arrays, leaving the garbage collector much work to do:
codes = codes.Take(index).Concat(codes.Skip(index + 1)).ToArray();
B) Use a generic list and just call
codes.Remove(code);