Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question Car driving through flag and the flag regenerates, not working

Discussion in 'Getting Started' started by LP1131, Feb 17, 2024.

  1. LP1131


    Sep 6, 2023
    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()

    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

    // Spawn a new object in a different spot
  2. BrianLH369


    Feb 26, 2022
    There are a few conditions:
    1. Both objects must have collider component
    2. At least one of the objects must have rigidbody component
    3. Both objects layers must collide with eachother in layer collision matrix(Edit/ProjectSettings/Physics)
    4. Object with OnTrigger function must have collider set to isTrigger

    -if both objects have collider set to isTrigger it wont collide
    -if trigger object has rigidbody you dont need to have collider on that exact object,
    it can be a child gameobject with collider or multiple colliders at different positions
    and they will all trigger the function in parent gameobject script