Search code examples
c#unity-game-engineinstantiation

My Gameobjects keep spawning right next to each other although I gave some offset


I followed the script from one of Unity tutorials. I'm trying to adjust it to according to my requirements. Any help is appreciated. Below is an Image of how it appears. I've given an offset to give some space while the object is being spawned but I feel like it doesn't work. Column min = 8, Column max = 20 enter image description here

 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class ObjectPooler : MonoBehaviour
    {

        private GameObject[] columnPool;
        public int columnSize =5;

        public GameObject columnPrefab;

        private Vector2 objectPoolPositionBeforeStart = new Vector2(12f, 0.42f); 

        public float timeSinceLastSpawned = 4f;
        public float spawnRate;
        public float columnMin, columnMax;
        private float spawnYPosition = 0.42f;
        private int currentColumn = 0;
        public float offset;
        // Use this for initialization

        void Start()
        {

            columnPool = new GameObject[columnSize]; 
            for (int i = 0; i < columnSize; i++)
            {
                columnPool[i] = Instantiate(columnPrefab, objectPoolPositionBeforeStart, Quaternion.identity);

            }
        }

        // Update is called once per frame
        void Update()
        {

                    timeSinceLastSpawned += Time.deltaTime;

          if (GameController.instance.gameOver == false && timeSinceLastSpawned >= spawnRate)
            {

                timeSinceLastSpawned = 0;
                float spawnXPosition = Random.Range(columnMin, columnMax) + offset;
                columnPool[currentColumn].transform.position = new Vector2(spawnXPosition, spawnYPosition);
                Debug.Log(spawnXPosition);
                currentColumn++;

                if(currentColumn >= columnSize)
                {
                    currentColumn = 0;
                }
            }
        }
    }

Solution

  • You are definitely on the right track I believe. I'm guessing you want the columns to keep going further away, for every column that has previously been spawned (so that each new colum has a position relative to the previous column).

    Currently, this is the code that determines the X position of a column.

    float spawnXPosition = Random.Range(columnMin, columnMax) + offset;
    

    This does not take other columns' positions into account. Perhaps you want to add the previous column's X position to this value?

    float spawnXPosition = columnPool[currentColumn - 1].transform.position.x + Random.Range(columnMin, columnMax) + offset;
    

    EDIT: Just make sure that columnPool[currentColumn - 1] doesn't go out of range! You don't want any original offset for the first column :)