- Home /
How do I pass through certain colliders but detect all collisions?
I am building a driving simulator for a competition, and my car has a JS script attached to it. The script detects collisions and prints the name of the object it collided with to the console. I have large obstacles such as parked cars, a shed, trash cans, signs and more that I want the car to collide with, print to console, and stop the car using normal collision physics. However, when the car hits the many cones on the course, I want it to detect each cone it hits, detect the collision and print to console BUT have the car continue moving as if the cone's not there. My car has a rigidbody component (non-kinematic) and none of the other objects have rigid bodies. Right now my collisions work just fine but if I run into a cone it stops the car and detects the collision or after setting the cone's collider to "Is Trigger", the car passes through the cone without detection of the collision. Each cone has it's own collider if that's helpful.
Here is the JS script on my car:
#pragma strict
function Start () {
print("The game has started!");
}
function Update () {
}
function OnCollisionEnter (col : Collision) {
var hitObject = col.gameObject.name;
print("I collided with the " + hitObject + " !");
}
How can I get the car to hit large objects (everything except cones) and detect the collision AND get the car to pass through cones yet still detect the collision?
Answer by _joe_ · Apr 13, 2015 at 11:38 AM
You need to use triggers in that case, Go to all your cones (inspector), and in the collider, tick "Trigger". Now your car will pass through the cones.
For you to be able to detect the collision, you need to use OnTriggerEnter instead of OnCollisionEnter (that takes a Collider instead of a Collision object)
so your code will be as such:
function OnTriggerEnter (col : Collider) {
var hitObject = col.gameObject.name;
print("I collided with the " + hitObject + " !");
}
For some reason when I try this code using UnityEngine;
public class SideTrigger : $$anonymous$$onoBehaviour
{
public Game$$anonymous$$anager game$$anonymous$$anager;
void OnTriggerEnter()
{
game$$anonymous$$anager.EndGame();
}
}
Yet it doesn't work for some reason it gives me an error: "NullReferenceExeption: Object reference not set to an instance of an object"