- Home /
The question is answered, right answer was accepted
Problem in Collider
Hello there, In my game, i have to collect my keys. So i have a Key Prefab with Box collider, and have Character Prefab with Character Controller, the Player tag is "Character", Key name is "Key". I have used OnColliderEnter function to destroy that key. But it doesn't work. Here is the Snippet Code.
void OnCollisionEnter(Collision Others)
{
if(Others.gameObject.name == "Key")
{
Debug.Log ("Key Collected");
Destroy (Others.gameObject);
Key_Text_Effect_Temp = Instantiate (Key_Text_Effect, new Vector3(transform.position.x, transform.position.y + 0.2f, transform.position.z + 0.5f), transform.rotation) as GameObject;
Key_Texture_Time += Time.deltaTime;
if(Key_Texture_Time >= 2)
{
Destroy (Key_Text_Effect_Temp);
Key_Texture_Time = 0;
}
}
}
I have aa other Object with Box Collider, its working fine with Character Object.
-Prasanna
Answer by Andres-Fernandez · Jun 12, 2014 at 06:44 AM
Have you checked that the name of the other gameobject is exactly "Key"? Because if you are instantiating them they may have names like "Key(clone)". Also, setting the key collider as isTrigger will help.
I suggest you use a layer for items (or even just for keys). That way, whenever you hit an object within that layer you don't have to worry about the names.
@Andres Fernandez.., sorry About that line, i changed if(Others.gameObject.tag == "$$anonymous$$ey")
ins$$anonymous$$d of if(Others.gameObject.name == "$$anonymous$$ey")
. It gives same result, not for this only; i created one new cube(default gameobject), and using like this, but this too giving the same thing.
If you are using tags make sure the key has tag "$$anonymous$$ey" (also I recomend using function gameObject.CompareTag) Have you checked the layer both objects are in? They need to be checked in the Collision $$anonymous$$atrix.
I checked all methods(Collision using Layers, Collision using Tags, Collision using Names), but it doesn't work.
If the collider is trigger, method should be OnTriggerEnter. Check the example, it's exactly what you should be using.
Answer by Prasanna · Jun 13, 2014 at 05:36 AM
@Andres Fernandez, thanks for your advise. I found the Solution, when the Character have Character Controller Component, the Syntax should be like this.
void OnControllerColliderHit(ControllerColliderHit Others)
{
if(Others.gameObject.tag == "Key_New")
{
Debug.Log ("Key Collected");
Destroy (Others.gameObject);
Key_Text_Effect_Temp = Instantiate (Key_Text_Effect, new Vector3(transform.position.x + 3.0f, transform.position.y + 0.2f, transform.position.z + 0.5f), transform.rotation) as GameObject;
Key_Texture_Time += Time.deltaTime;
if(Key_Texture_Time >= 2)
{
Destroy (Key_Text_Effect_Temp);
Key_Texture_Time = 0;
}
}
}
So this will Help your Character to Collide with other Collider like Box Collider, Capsule Collider, etc..,
-Prasanna