Home > Enterprise >  Can you spawn gameobjects and move them to an x position that is added by the last one
Can you spawn gameobjects and move them to an x position that is added by the last one

Time:04-01

I am very new to Unity game development and was just curious if there was any way to spawn a gameobject in a position then the next game object in that position added like for is 1 then the next one will be 2 then 3 and so on.

CodePudding user response:

From inspector you will need to assign the prefab and set the objectCount and spacing values. This will spawn the objects along the positive x axis starting at zero. If you want to move the objects along a different axis, change the x in position.x to one of the other vector3 components (y, z). To move along the axis in the opposite direction, invert the spacing value (eg. from 1 to -1).

using UnityEngine;

public class ObjectSpawner : MonoBehaviour
{
    public GameObject prefab;
    public int objectCount;
    public float spacing;

    void Start()
    {
        var position = new Vector3();

        for (int i = 0; i < objectCount; i  )
        {
            Instantiate(prefab, position, Quaternion.identity);
            position.x  = spacing;
        }
    }
}
  • Related