Hey folks,
I need your help regarding the Destroy method.
I want to destroy a car, when it has driven by and it cannot be seen in the camera anymore.
I used a Trigger to destroy the “Tile” when it passed by but as the cars are in a prefabList, I cannot select a specific object to destroy.
I made a video to demonstrate my problem and attached my code for the car spawning below.
Thank you so much for your help!
Kind regards
Tim
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarSpawn : MonoBehaviour
{
List<GameObject> prefabList = new List<GameObject>();
public GameObject carSpawnGreen;
public GameObject carSpawnBlue;
public GameObject carSpawnPolice;
public GameObject carSpawnBus;
public GameObject carSpawnVan;
public GameObject carSpawn1;
public GameObject carSpawn2;
public GameObject carSpawn3;
public GameObject carSpawn4;
public GameObject carSpawn5;
public GameObject carSpawn6;
public GameObject carSpawn7;
public GameObject carSpawn8;
public float speed = 30F;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Waiter());
prefabList.Add(carSpawnBlue);
prefabList.Add(carSpawnGreen);
prefabList.Add(carSpawnPolice);
prefabList.Add(carSpawnBus);
prefabList.Add(carSpawnVan);
prefabList.Add(carSpawn1);
prefabList.Add(carSpawn2);
prefabList.Add(carSpawn3);
prefabList.Add(carSpawn4);
prefabList.Add(carSpawn5);
prefabList.Add(carSpawn6);
prefabList.Add(carSpawn7);
prefabList.Add(carSpawn8);
}
IEnumerator Waiter()
{
int prefabIndex = Random.Range(0, 8);
int wait_time = Random.Range(1, 5);
yield return new WaitForSeconds(wait_time);
int carPicker = Random.Range(1, 3);
if (carPicker == 1)
{
Instantiate(prefabList[prefabIndex], new Vector3(44.49F, 0.85F, 100F), Quaternion.Euler(new Vector3(0F, 90, 0F)), transform);
}
else
{
Instantiate(prefabList[prefabIndex], new Vector3(47.21F, 0.85F, 100F), Quaternion.Euler(new Vector3(0F, 90, 0F)), transform);
}
StartCoroutine(Waiter());
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.back * speed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
//Destroy cars when touching the trigger
}
}
euu0d8