- Home /
When im instantiating a prefab with c#, it creates more and more clones at once. I only want 1 at a time.
I have a really simple code.
void Update () {
if(Input.GetButtonDown("Fire1")){
GameObject instance = Instantiate(Resources.Load<GameObject>("Pipes")) as GameObject;
}
}
When pressing fire, it will first make one clone of the prefab. Next time it will create 2 clones, then more than 2 clones, and then more and more. After 6 or 7 times it will create over 100 clones at once.
What can be the problem?
Answer by YoungDeveloper · Apr 24, 2014 at 03:19 PM
Hi, please format your code, there's a button 1010, i did it for you this time.
What comes to your problem, instead of instantiating from resources try from public variable or cache it in Start().
public GameObject obj; //drag and drop GameObject in inspector
void Update () {
if(Input.GetButtonDown("Fire1")){
GameObject instance = Instantiate(obj) as GameObject;
}
}
Instantiating from resources is not the problem (and is the standard way of doing it.)
Yea, i didn't say that was the problem, as i said "try from public variable", if result would be the same it would mean problem is else where or author didn't post whole code.
Answer by socialspiel · Apr 24, 2014 at 04:01 PM
Where do you have attachted this script?
If it's attached to the prefab you are instantiating then it will have an new instance of this script that will spawn another one and so on..
Answer by perchik · Apr 24, 2014 at 04:05 PM
It sounds like your script is attached to the object that you instantiate. When you instantiate it the first time, it creates a new object in the scene with the same script. Now when you click, both objects run and instantiates two new ones). Now there's 4... etc
Sounds like you need to move the script to something that is not instantiated every time.
Your answer