- Home /
How can I destroy my Instance without renaming it?
In my game, I instantiate weapons when I equip them. I have a list of transforms as my list of weapons, and my selected weapon is also a transform. when I press the key I need to press in order to equip a weapon, it instantiates the weapon into my players hand. The problem I have is with destroying the equipped weapon when I want a different weapon. Every time I press the "switchWeapon" key, it cycles through my list and gives me the next weapon in the list.
How the h**l do I upload code on here?
My problem is specifically with those last couple lines ^^ I'm getting an "Object reference not set to an instance of an object"
Any help?
You copy-paste the code and then use the square "101-010" button to format it so our eyes don't bleed trying to read it. ^_^
I would like to note that the method you're using may not be the most effective; since you're instantiating and destroying things when you know how many of them exist.
$$anonymous$$eeping the GameObjects in an array and hiding them when not in use may actually be a more efficient way to do things. It would be easier on your memory management too, leaving more performance for amazing graphics/physics.
Answer by Meltdown · Aug 12, 2012 at 08:24 PM
Each weapon should be a prefab in your project.
When you instantiate it, the code should look something like this...
[SerializeField] GameObject _myWeaponPrefab;
GameObject weapon = GameObject.Instantiate(_myWeaponPrefab, player.transform.position, Quaternion.identity);
You now have a reference to the instantiated weapon, which you can destroy by simply calling
Destroy(weapon);
So I integrated this into my current code, but it's still not working. There's no errors, but the sword isn't being destroyed, either. I know the function is being called though, because I put a debug statement into it and the Debug is co$$anonymous$$g through.
Answer by Budoray · Aug 14, 2012 at 05:53 AM
Greg, you solved my issue, but I can't vote for your answer. My issue was that I had a prefab declared as a Transform. I cast it from the Instantiate method as a GameObject with no errors or warnings. Called Destroy with no errors or warnings. However, the prefab would remain on the screen. Declaring my prefab as a GameObject fixed that issue. Many thanks.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Pass a copy of a GameObject as variable to another script? 1 Answer
How to delete instantiated GameObject 4 Answers
Instantiate and Destroy an object while crossing a line with its clone also 1 Answer
Destroy a specific instantiated clone? 2 Answers