- Home /
function OnCollosionEnter problems
so I have this script so that when the player touches a key, it changes a variable from 0 to 1 and destroys the key. but for some reason, I can't get unity to recognize the collision between the player and the key.
i made a script
function OnCollisionEnter (col : Collision)
{
Debug.Log("hit!");
}
and what this did was show me everything that the player was colliding with. and it worked on everything except for the object of my key (which is just a sphere)
this is my full code for what i want to happen when the player gets the key
var locklevel : int = 0;
var keyGet : AudioClip;
function OnCollisionEnter (col : Collision)
{
if(col.gameObject.name == "aKey")
{
Debug.Log("hit!");
locklevel = 1;
audio.PlayOneShot(keyGet);
Destroy(col.gameObject);
}
}
this script is attached to the first person controller prefab. why won't it recognize a collision with the key? (the key is also instantiated and not placed from the beggining, if that makes a difference)
Does the key have a big enough collider ? Does your player have a collider ? if so can they both touch ? also maybe the key collider is set to Trigger ? please answer these to have a clearer idea of whats happening
Try using tags and check for those ins$$anonymous$$d, you will often notice that instantiated prefabs with be called something like "a$$anonymous$$ey (clone)" rather than just "a$$anonymous$$ey", so tag you rkey prefab as "$$anonymous$$ey" and do if(col.gameObject.tag == "$$anonymous$$ey") ins$$anonymous$$d.
the key is simply a sphere, with a sphere collider not set to trigger. for some reason adding a rigidbody to the player fixed everything
Answer by Fabulous-Design · Aug 24, 2014 at 03:52 PM
make shure you got a (sphere/box)collider on the key.
Your answer
Follow this Question
Related Questions
JavaScript - Reset Characters Position 2 Answers
Help with OnCollision 2 Answers
Adding sound javascript in unity2d 1 Answer
OnCollisionEnter Problem 1 Answer