Hello. I have a painfully noobish question for you. I’m making a projectile prefab and script, and I’m trying to get the projectile to destroy itself when it collides with solid objects (Terrain, solid cubes, etc). This is the C# code I’m using:
void OnControllerColliderHit(ControllerColliderHit hit)
{
Destroy(transform.gameObject);
}
This is what my projectile object looks like in the inspector:
This seems to do absolutely nothing, the projectile simply goes through everything. My guess is that there is some dumb check box that I have to check in the game editor, but I feel like I’ve tried everything.
I’ve also used OnCollisionEnter and OnTriggerEnter, but neither seemed to do anything. Also, I’d like to know the difference between these functions because they sound pretty similar the way they are described.
You need a rigidbody component on your projectile otherwise it is treated as a static collider, and 2 static colliders do not register collisions against each other.
If driving the projectile purely through code, turn on “isKinematic” on your rigidbody.
Use OnCollisionEnter to detect collision, only use OnTriggerEnter if you have “Is Trigger” set on a collider. The difference is an object won’t actually bounce off a trigger, it will pass through it.
I’ve tried adding a rigidbody to the projectile, I turned on isKinematic, and used OnCollisionEnter, but it is still not registering. The console is giving me the following message:
I don’t know what that means. I’m still now sure what the problem is. Do you know of any really simple examples (video or unity package) that I could look at? Thanks for your input.
Yes, it means that your parameter needs to be of type “Collision”; you are trying to use a type “ControllerColliderHit” which it doesn’t understand. Try this:
void OnCollisionEnter(Collision hit)
{
Destroy(transform.gameObject);
}
Turn off isKinematic. That would mean that your object is controlled by code, but will still give events. You want a bullet, which is a physics controlled object. The error suggests that you are not using the function correctly…
However, bullets are faster than normal physics, so your checks should be done with a Ray or line cast with no collisions involved.
Here is some code illustrating the basics.
private var lastPosition : Vector3;
funciton Start(){
if(collider)
Destroy(collider);
lastPosition = transform.position;
}
function Update(){
var hit : RaycastHit;
if(Physics.LineCast(lastPosition, transform.position, hit)){
// you could do something with the hit here
Destroy(gameObject);
}
lastPosition = transform.position;
}
Thanks, I changed the function name but forgot to change the parameter. That seemed to do it. Thank you very much for your help, sir.