My code is instantiating many prefabs, i only want one.
I have the player press E to stab with their sword. Which instantiates a trigger collider around the sword they cant see. If a monster collides with it they take damage and the whole bit. The problem is, the way I coded it spawns maybe 10 prefabs a second resulting in the monster taking a lot of damage really fast. I messed around and coded to destroy the prefabs all but just as fast as they come in but it still bugs a good bit. What should i do to only instantiate one?
Code attached to sword only deals with knockback.
Animation code attached to player says "attacking" bool to true when player presses E, and instantiates the prefab.
void FixedUpdate () {
if (Input.GetKey (KeyCode.E)) { attacking = true; attack(); }else attacking = false; if (Input.GetKeyUp (KeyCode.E)){ attacking = false; }
-Here is the instantiate code ** (also in the animation script)
void attack(){
if (OneHandEquipped){
instantiatedObj = (GameObject) PhotonNetwork.Instantiate(wepTriggerPrefabName, wepPoint.position, wepPoint.rotation, 0);}
Destroy(instantiatedObj, time);
}
Answer by VMohan · Sep 05, 2015 at 03:20 AM
Instead of Input.GetKey use Input.GetKeyDown. Input.GetKey is called any time the button is pressed (which means you will call attack ~60 times if you hold the key for just one second), whereas GetKeyDown is called just once.
Ah yes thankyou, I remember I started with this and then changed to just Get$$anonymous$$ey and now I see why. The animation cancels and the prefab gets destroyed too quick. I put it in Update ins$$anonymous$$d of FixedUpdate and its still way too quick.
Anyway to let the animation play out? I want to be able to move and stab and at the end of the animation the bool will switch off ins$$anonymous$$d of just right away. Do you know how to achieve this?
I would use a coroutine, where you wait a set amount of time (while the animation plays) and then perform all the actions you want such as switching the bool and destroying the gameobject.
If you want another best answer im about to post that question with the current code i have.
Your answer
Follow this Question
Related Questions
Destroy instatiate object on trigger enter / collision,destroy instantiate prefab on trigger enter 0 Answers
is the Character Controller a Collider? 2 Answers
OnTriggerStay Doesn't work if not moving 2 Answers
Can't Instantiate an object as child of another 1 Answer
Cannot destroy the SphereCollider on Instantiated Objects 1 Answer