- Home /
Can't seem to get collision to work
So I have a rocket prefab that instantiates every time you press the spacebar. It's supposed to be destroyed when it goes out of a camera's view, or hits the terrain. I can't get it to work. Take a look at my code.
#pragma strict
var terraintarget : GameObject;
private var invis : boolean = false;
private var terraincollide : boolean = false;
function OnBecameInvisible() {
invis = true;
}
function Update(){
if(invis === true){
Destroy(gameObject);
}
if(terraincollide === true){
Destroy(gameObject);
}
}
function OnCollisionEnter (collision : Collision) {
if(collision.collider.name === "Ground"){
Destroy(gameObject);
}
}
I tried changing it to print to the console the name of the colliders it hits, but that won't work either.
Answer by Narv · Dec 07, 2013 at 05:20 PM
some sanity checks first:
does your rocket have a collision on it? box collider, sphere, etc?
you are using a variable called terraincollide but never set the value to true but then you are checking if it's true..
you have a public variable for targetterrain. I assume you are setting that in the inspector but never reference it in the code.
the terrain you are hitting, is it a unity terrain or mesh? does it have a terrain collider or other collider of shorts?
have you tried using == instead of === in case unity is doing something funky with datatypes?
The rocket does have collision on it. Both variable issues are just from me forgetting about them. Neither of them are supposed to be used right now at least. The terrain is a Unity Terrain with a Terrain Collider on it.
I tried what you said, and nothing changed.
which case happens most often? invisible or collision? I found this note on the method for OnBecameInvisible:
Note that object is considered visible when it needs to be rendered in the scene. It might not be actually visible by any camera, but still need to be rendered for shadows for example. Also, when running in the editor, the scene view cameras will also cause this function to be called.
as for the collision, you said you tried printing the name of the collider and it didn't work... wrong collider name or not printing anything at all? like a Debug.log("$$anonymous$$eh");
the other thing is do you have a rigidbody on the rocket? (required for collision) or is anything checked as "use as trigger" or whatever the ter$$anonymous$$ology is? I don't have unity open infront of me at the moment.
THAN$$anonymous$$ YOU SO $$anonymous$$UCH, OH $$anonymous$$Y GOD! I.. I didn't know you needed a rigidbody for it to work...
haha no problem :) guess I should have put that at the beginning list :p yeah collision in unity in a scripting sense is for physics.. where as a non-physics based collision uses triggers.
Your answer