- Home /
Remove and Add to List By Name aad
Hello Everyone
i have a 2 List
1 Called : freeSpawnPoints
2 Called : TheNewSpawnPoints
both of them Contain Transforms
..
now.... i want to Add Something from List1 to List2 by using the name of transform
for Example
i have List1 Transform Called "T1"
i want to move "T1" Transform from List1 to List2
Here is my Idea Code :
freeSpawnPoints.Add(TheNewSpawnPoints.Find("T1"));
//AND i need Same way to remove it from the List
TheNewSpawnPoints.Remove("T1");
i hope u got my poing.. and thanks
You can just use a for loop like this. It loops trough the list of objects and get the object with the wanted name, and then just add it to the other list. Works the same way with delete:
//haven't been tested.
foreach (Transform t in freeSpawnPoints)
{
if(transform.name.Equals("T1")){
TheNewSpawnPoint.Add(t);
}
}
If you want better performance you should have a look at HashTable maybe. :) Good luck
i'm not sure.. but its not working
i also guess u mean this
if(t.name.Equals("T1")){
//not
if(transform.name.Equals("T1")){
anyway tried both but didnt work
Error :
InvalidOperationException: Collection was modified; enumeration operation may not execute.
in this line :
foreach (Transform t in TheNewSpawnPoints)
. thx for help
Yeah of course. Silly me. Don't have the possibility to test anything here. The Exception is because we are trying to modify the collection while looping trough it.
Look at this stackOverFlow answer. $$anonymous$$ight help you. I think i'm gonna keep away from coding any more without a debugger! :P
http://stackoverflow.com/questions/7340757/c-sharp-list-removing-items-while-looping-iterating
easier answer please :) still cant get it ] his answer cant work on Transforms
Answer by vividhelix · Jul 23, 2013 at 08:27 AM
Try this:
TheNewSpawnPoints.RemoveAll(x=>x.name=="T1");
Alternatively, this should work as well:
var t1 = TheNewSpawnPoints.Find("T1");
freeSpawnPoints.Add(t1);
TheNewSpawnPoints.Remove(t1);
Thanks. the first code working fine
and for second code in C# i dont know what i should change "var" to
any way its works. ty