- Home /
instantiate and destroy object with the same button
Hello
I need to destroy and instanciate the same object with the same button, right now Im clueless on how to do this. I have two weapons in my game, one its a pistol and the other a shotgun, I want the pistol to disappear when I hold the right mouse button and reappear when I release the right mouse button.
Basically I want to use the right mouse button to change weapons, while the right mouse button its hold the pistol disappears and the shotgun appears, when you release the right mouse button the opposite happends.
How can I do this?
And the bonus question (this one gives you extra points! hahaha): The objects I destroy and instanciate need to be prefabs? Im asking because Im guessing if I destroy an object it would vanish for good from the scene, right?
Destroying the object and instantiating the weapon would be a really inefficient way of doing this. You just need to disable the object, any scripts attached and move it out of view when not in use.
You could possible have a weapons class that can set the shotgun object as the active object when the right mouse is down and the pistol as the active object when not, so the same component controls the weapon change and all its doing is disabling one and switching to the other.
Hope that makes sense.
Answer by robertbu · Feb 03, 2013 at 07:40 PM
As mentioned above by @raycosantana, you don't need to destroy and Instantiate each time. You can enable/disable or show/hide.
To show/hide: renderer.enabled = true/false To enable/disable: gameObject.SetActive(true/false)
As for making the guns visible/invisible, you can do something like:
if (Input.GetMouseButtonDown(1))
{
// Hide the pistol, show the shotgun
}
else if (Input.GetMouseButtonUp(1))
{
// Show the pistol, hide the shotgun
}
Note the GetMouseButtonDown/Up methods return true only during the frame the mouse buttons change state.