Need help with my Instantiate

Okay, so the problem here is not that the Instantiate function not working, but with me needed to have more than one carPos (the only one at the minute being -3.4, 3.4). Using these values works fine for all of my vehicles except one that is two cars side by side, as sometimes this car will overlap onto the side of my road.

Here is a photo of what Is happening. Is there anyway I can get this specific vehicle in my array to use the Pos -3.0, 3.0 or something similar to keep it within bounds?

using UnityEngine;
using System.Collections;

public class carSpawner : MonoBehaviour {

    public GameObject[] cars;

    public uiManager ui;
    int carNo;

    public float maxPos = 3.0f;
    public float delayTimer;
    float timer;


    void Start ()
 
    {

        timer = delayTimer;
    }
 
    void Update ()
 
    {
        timer -= Time.deltaTime;
        if(timer <= 0)
        {
        Vector3 carPos = new Vector3(Random.Range(-3.4f, 3.4f), transform.position.y,transform.position.z);
     
     
        carNo = Random.Range (0,7);

        Instantiate (cars[carNo], carPos, transform.rotation);



        timer = delayTimer;




        }

Well first generate carNo and if it is the 2car then set carPos range 3.0 to -3.0 else keep 3.4

EDIT to generate randomrange of carpos use if carno is two cars set range of 3.0 else 3.4

void Update ()
   
    {
        timer -= Time.deltaTime;
        if(timer <= 0)
        {
        Vector3 carPos = new Vector3(Random.Range(-maxPos, maxPos), transform.position.y,transform.position.z);
        Vector3 DuocarPos = new Vector3(Random.Range(-3.0f, 3.0f), transform.position.y,transform.position.z);
       
       
        carNo = Random.Range (0,7);

        Instantiate (cars[carNo], carPos, transform.rotation);

            if(carNo == 7)
            {
                carPos = DuocarPos;
            }

        timer = delayTimer;

tried this and had no luck

You’re changing carPos after instantiate?

I tried the same code before the instantiate and still had no luck

Corect me I’d I’m wrong. But doesn’t Random.Range(0,7); return etter 0,1,2,3,4,5 or 6, not 7?

So like this?

void Update ()
  
    {
        timer -= Time.deltaTime;
        if(timer <= 0)
        {
        Vector3 carPos = new Vector3(Random.Range(-maxPos, maxPos), transform.position.y,transform.position.z);
        Vector3 duoCarPos = new Vector3(Random.Range(-3.0f, 3.0f), transform.position.y,transform.position.z);
      
      
      
        carNo = Random.Range (0,7);

            if(carNo == 6)
            {
                carPos = duoCarPos;
            }

        Instantiate (cars[carNo], carPos, transform.rotation);


        timer = delayTimer;
1 Like