- Home /
Object not responding to OnTriggerEnter()
So I'm trying to get a car to respawn at a general location some short time after passing a collider. For some reason, the script works if I walk into the collider with FirstPersonController. However it won't affect the car. Interestingly, if I test carReset() with "p" as shown in Update() after the car passes the collider, I get the error: "NullReferenceException: Object reference not set to an instance of an object". I'm fairly new to scripting and unity and I can't figure out why this wouldn't be working but still affects FirstPersonController.
Here's the script:
public class CarRespawn : MonoBehaviour {
GameObject car;
void Update(){
if (Input.GetKeyDown ("p")) {
carReset ();
}
}
void OnTriggerEnter(Collider c_car){
car = c_car.gameObject;
Invoke ("carReset", Random.Range (0.5f, 3.0f));
}
void carReset(){
car.transform.position = new Vector3 (Random.Range (-6.0f, -12.0f), 1.16f, Random.Range(25.0f, 60.0f) );
}
}
Answer by JaredHD · Apr 28, 2017 at 08:24 AM
Ok, So this is what i did. You need 1 car with a Rigidbody. 1 Barrier with a box collider that has Is Trigger
enabled. Then use the code below and attach that to the barrier.
using UnityEngine;
public class TriggerEnter : MonoBehaviour
{
GameObject car;
private void OnTriggerEnter(Collider other)
{
if (other.name == "Car" || other.gameObject.tag == "Car")
{
Debug.Log("Hit");
car = other.gameObject;
Invoke("ResetCar", Random.Range(0.5f, 3f));
}
}
private void ResetCar()
{
car.transform.position = new Vector3(Random.Range(6.0f, -12.0f), 1.16f, Random.Range(25.0f, -60.0f));
}
}
Note: The car must be named "Car" or have a tag called "Car"
That's it. It moves the car when it hits the barrier. I'm expecting that your problem was that the car didn't have a rigidbody.
The null reference exception was due to the fact that your car never actually registered as hitting the collider, and so it never assigned the car.
Answer by jmarchuk · Apr 28, 2017 at 11:17 AM
@JaredHD Ah alright, thanks! So to be clear, the collider won't be detected unless the object it's attached to also has a rigidbody? Why is that?
@jmarchuk I'm pretty sure colliders won't be detected unless you have a rigidbody. Here's a website that explains how you can use a rigidbody to detect a trigger but ignore the physics, Here's another nice explanation as well. Basically as the second website says, Using Bampf answer,
"You can indeed have a collider with no rigidbody. If there's no rigidbody then Unity assumes the object is static, non-moving. Unity does not bother testing for collisions BETWEEN static objects. As you can imagine, this is very efficient if you have lots of scenery the player can bump into."
Hope that helps. Please don't forget to ensure that you accept the answer if it was right.