- Home /
can add to a list but not remove
I have three scripts: a populationmanager, spawner, and characterai for destroying. I can spawn a prefab and add it to my population list, but I can't seem to figure out how to remove it from the list before destroying. Any suggestions?
Here's some of the code:
Populationmanager:
public List<GameObject> civpop;
Spawner:
GameObject obj = middle[Random.Range(0, middle.Length)];
Instantiate(obj, new Vector3(transform.position.x+5, transform.position.y, transform.position.z), transform.rotation);
obj.GetComponent<CharacterAI>().popmanager = popmanager;
popmanager.civpop.Add(obj);
CharacterAI:
IEnumerator Die()
{
popmanager.civpop.Remove(gameObject);
yield return new WaitForSeconds(5);
Destroy(gameObject);
}
Any help is greatly appreciated!
Answer by ShadyProductions · Feb 16, 2020 at 07:02 PM
I don't see how ragefordragons answer is related to the problem, Remove function uses the hashcode of the gameobject, each gameobject has a unique hashcode so it should remove it.
Infact your problem is that you add the wrong reference to the list.
GameObject obj = middle[Random.Range(0, middle.Length)];
Instantiate(obj, new Vector3(transform.position.x+5, transform.position.y, transform.position.z), transform.rotation);
popmanager.civpop.Add(obj);
you are adding the reference of middle[Random.Range(0, middle.Length)]; to the list, and not the new object you just instantiated.
GameObject obj = middle[Random.Range(0, middle.Length)];
obj = Instantiate(obj, new Vector3(transform.position.x+5, transform.position.y, transform.position.z), transform.rotation);
popmanager.civpop.Add(obj);
Instantiate method will return the new object you created, if we then assign this to the obj variable we should be adding the correct reference to the list. This example should work.
Your answer
Follow this Question
Related Questions
Help: items not getting added to list. 1 Answer
Check if Exists and if so, Add it to Other List 1 Answer
How to add an item to a list with a class/uJS struct? 1 Answer
A node in a childnode? 1 Answer
Remove and Add to List By Name aad 1 Answer