- Home /
destroy GameObject without removing reference in list
Hello
i'm working on a weapon pickup system so your character can have multiple weapons. the problem is when i pickup a weapon i can add it to the list but then i want to destroy the GameObject from scene here it is also removed from my list even when i put the weapon into a local variable and ad that to the list and destroy the original GameObject
// weapon list
List<AWeapon> Weapons = new list<AWeapon>();
// add weapon method
public void AddWeapon(AWeapon newWeapon)
{
AWeapon newWeaponClone = newWeapon;
Weapons.Add(newWeaponClone);
Destroy(newWeapon.gameObject));
}
thanks in advance,
Answer by SirPaddow · Jul 28, 2019 at 06:21 PM
You should try to understand how objects in C# work. Your object is unique, even if you create a new AWeapon variable that references that object, it only gives a "second name" to one same object. So if you destroy the object named "newWeapon", you also destroy the object named "newWeaponClone" (which is in no way a clone).
Now, to solve your problem. It really depends on what you want to do. Why do you need to destroy this object?
Maybe you could only deactivate the object, like this:
Weapons.Add(newWeapon);
newWeapon.gameObject.SetActive(false);
If you really need a clone, that's how we clone a gameObject
AWeapon newWeaponClone = Instantiate(newWeapon);
Weapons.Add(newWeaponClone);
Destroy(newWeapon.gameObject)); // in this case, newWeaponClone is not destroyed
If you want a reference to a gameobject that you don't want in your scene, you should check prefabs, here: https://docs.unity3d.com/Manual/Prefabs.html