Search code examples
c#unity-game-enginespritegame-physics

How do you consecutively spawn objects in unity using instantiate?


So I want to spawn a sprite over and over again without any gaps. so like after an object spawns, another does to give the illusion that they are joined over and over.

I have no working code currently, so I would love some help.

unity2d and visual studio


Solution

  • If you want to spawn it next too each other use this:

    float timer = 1;

    Vector2 objPos;
    
    public GameObject prefab;
    
    void Start()
    {
        objPos = new Vector2(0, 0);
    }
    
    void Update()
    {
        timer -= Time.deltaTime;
    
        if (timer <= 0)
        {
            Instantiate(prefab, objPos, quaternion.identity);
    
            objPos = new Vector2(objPos.x + 0.5f, this.transform.position.y);
    
            timer = 1;
        }
    }
    

    this script places a cube every 1 sec 0.5 int the x forward.