Home > Back-end >  How can i clone an object one by one in unity
How can i clone an object one by one in unity

Time:08-02

So basically i wanted to learn about instantiate and I have tried this code below:

public Transform spawnpos;// the position where i wanted to clone my sphere
void Update()
{
    if (Input.GetKeyDown("q"))
    {
        Instantiate(gameObject, spawnpos.position, spawnpos.rotation);
        Destroy(gameObject, 2);
    }
}

the thing is, when i press "q" it does spawn a sphere and gone in about 2 secs, but if i continously press "q" the amount of clones spawned are getting bigger as i press and it wont be destroyed after 2 seconds.

In Conclusion, how can i spawn a sphere when i pressed "q", and it will spawn 10 if i pressed "q" 10 times

tysm for reading this far! have a nice day! :)

CodePudding user response:

First thing's first, you can't instantiate the gameobject to which this script is attached through this script because:

If you instantiate a gameobject, there will be two gameobjects in the scene and both will be having this script. Hence if you press Q again, two gameobjects are instantiated.

Solution:

Create an empty gameobject in the scene and create a new script ObjectSpawner.cs and attach it to this empty gameobject.

public class ObjectSpawner : MonoBehaviour {
    public Transform spawnpos;// the position where I wanted to clone my sphere
    public GameObject sphere;// gameobject you want to spawn
    void Update() {
        if (Input.GetKeyDown("q")) {
            GameObject obj = Instantiate(sphere, spawnpos.position, spawnpos.rotation);
            Destroy(obj, 2);
        }
    }
}

In the above script as you can see there's a field for the sphere gameobject. Drag it to the slot in the inspector.

  • Related