Instantiate not working correctly

Hello unity community!
I am trying to make a tower android game so when the players is touching the screen the tower goes from first floor up so far so good. Did this and its working perfectly but also I need the tower to be infinitive generated without overlapping.This is not working correctly I intantiate objects but they overlap one over another and I need them to be perfectly one after another . There is an Image attached for better understanding.


The code I am using for Mooving up which is working fine is this:

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

public class sliceIt : MonoBehaviour
{
    public float movementSpeed = 5;
    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            transform.position += Vector3.up * Time.deltaTime * movementSpeed;
         
        }

    }
}



[SPOILER="This is the code that is not working and overlaps instantiated prefabs. Basically I am trying to make Infinitive Level Generator."][/SPOILER]






[code=CSharp]public class spawnIt : MonoBehaviour
{
    public Transform prefab;
    public Transform spawnHere;
    public bool spawnnow=true;
    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (spawnnow == true)
            {
                Instantiate(prefab, spawnHere.position, Quaternion.identity);
            }
        }

    }
    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag != "spawnHere")
        {
            spawnnow = false;
        }
        else
        {
           
            spawnnow = true;
        }
    }


}

I used :

  void OnCollisionExit(Collision col)
    {
     
      
            Instantiate(prefab, spawnHere.position, Quaternion.identity);
       
    }

this worked but now when it goes too fast there is space between the cubes

Don’t calculate where to put the next tower based on how much time has passed; always put it a fixed distance from wherever the last tower went. (Store either the last tower or the last tower’s position in a variable.)

2 Likes