I am creating my first game in unity where the aim of the game is to drive a taxi around a city to a flag which generates at a random position in the map. When the taxi reaches and collides with the flag, the flag should be regenerated elsewhere on the map in order for a new mission to be started. I have written the script, however nothing happens when the car collides with the flag when I test it. What is the reason for this? I will post my script below:
using UnityEngine;
public class RandomObjectSpawner : MonoBehaviour
{
public GameObject objectToSpawn; // The object you want to spawn
public int gridSize = 100; // The size of the grid
public string carObjectName = “taxi1”;
private GameObject spawnedObject; // Reference to the spawned object
void Start()
{
SpawnObject();
}
void SpawnObject()
{
// Generate random coordinates within the grid
float randomX = Random.Range(0, gridSize);
float randomY = Random.Range(0, gridSize);
// Calculate the position in Unity coordinates
Vector3 spawnPosition = new Vector3(randomX, 0, randomY);
// Instantiate the object at the random position
spawnedObject = Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);
Debug.Log(“Object spawned!”);
}
void OnTriggerEnter(Collider other)
{
// Check if the car (or another object with a collider) entered the trigger
if (other.CompareTag(carObjectName))
{
// Destroy the current spawned object
Destroy(spawnedObject);
// Spawn a new object in a different spot
SpawnObject();
}
}
}