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) );
}
}
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.
@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?