- Home /
Object Instantiating to many objects
Hello, I have a gameobject that if a if statement applies to my script a object will Instantiate, but when i run the game it instantiates way to many and does not stop making the object what am i doing wrong. Here is my code. BTW i want to keep the way its setup but just only have it Instantiate the model one time.
public Transform Weapon1GO; public string Weapon1;
public GameObject Tac50;
public Transform WeaponSpawn;
void update(){
Weapon1 = "Tac50"; WeaponSpawn = transform.Find("Main Camera/WeaponWalkHolder/WeaponJumpHolder/WeaponSwayHolder/WeaponRecoilHolder"); if(Weapon1 == "Tac50"){ if(Weapon1GO == null){ GameObject weapon1I = Instantiate(Tac50, transform.position,transform.rotation) as GameObject; weapon1I.transform.parent = WeaponSpawn;
}
} }
Update I know why this is happening but i dont know how to stop the instantiating, ive tried bools. Please some one tell me how to fix this.
Please format your code. If you do not know how, watch the tutorial video and look at the FAQ: http://video.unity3d.com/video/7720450/tutorials-using-unity-answers http://answers.unity3d.com/page/faq.html
Answer by Nerull22 · Mar 25, 2013 at 03:29 AM
All right, if I'm reading your code correctly then you have two if statements. The first if statement is to check and see if Weapon1 == "Tac50". But that if statement is kind of a moot point since you're defining Weapons1 = "Tac50" at the beginning of every update. And then the next if statement is Weapon1GO is null, and since I don't see it being set to anything at all at any point, then both these if statements are going to remain true at all times.
So a new object will be instantiated at every frame. You need to make one of those if statements false when you get into them. You've basically made an infinite loop with if statements. I can't really tell you how to fix the problem since I'm not sure what this is supposed to do or how it all works together with the rest of your project. But that's where I see your problem residing.
Yes I know that its being instantiated every frame but how can i have it not i tried i bool, tried making the second if statement false, but nothing will work and i cant change the first if statement does any one know how to fix this
If you want a quick and dirty fix. $$anonymous$$ake a new boolean variable. And make the second if check:
if(Weapon1GO == null && !newBool)
{
newBool = false;
//Do all other things here
}
That will stop it from running again after the first time.
Your answer
![](https://koobas.hobune.stream/wayback/20220613095029im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
FPS Instantiate position. Please help? 0 Answers
Done Something Wrong, Don't Know What I've Done? 2 Answers
Help! NullReferenceException? 3 Answers
Network.Instatiate Problem 0 Answers