Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[SOLVED] CollisionEnter/Exit doesn't work

Discussion in 'Scripting' started by Zavalichi, Oct 20, 2018.

  1. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    Hi guys,

    Imagine you have a city with a lot of cars, but these cars can move through another car and you want to change the speed to avoid this.

    What I tried to do:
    1. Find the distance between the current car and the next car, but I don't think this is the best idea so I tried method 2.

    2. Unsing collider: I created a script: SpeedChange and I attached to every car, but it doesn't work. Can you help me :( ?

    Code (CSharp):
    1. public class SpeedChange: MonoBehaviour
    2. {
    3.     private void OnCollisionEnter(Collision collision)
    4.     {
    5.         this.GetComponent<CarManager>().speed = 14f;
    6.         Debug.Log("OnColisionEnter");
    7.     }
    8.  
    9.     private void OnCollisionExit(Collision collision)
    10.     {
    11.         this.GetComponent<CarManager>().speed = 40f;
    12.         Debug.Log("OnColisionExit");
    13.     }
    14. }
    upload_2018-10-20_13-41-4.png
     
  2. SVKsuli

    SVKsuli

    Joined:
    Mar 23, 2014
    Posts:
    63
    the first thing I thought, doesnt have your car collider set to trigger? and have your car rigidbody?
     
  3. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    Thank you, the RigidBody and Trigger was the problem.

    To work I had to add Mesh Collider to my terrain, do you know why Terrain Collider doesn't work?
     
  4. SVKsuli

    SVKsuli

    Joined:
    Mar 23, 2014
    Posts:
    63
    terrain collider looks like it need terain data to work, i never try to create it but you can see how it work when you create new Terrain from unity menu - GameOjbect - 3DObject - Terrain. But using mesh collider is ok.