- Home /
Cannot get Collider event of different object
I have a scrip attached to GUI canvas in this script I perform various operation related to game status.
Now I want to detect the hit of a bullet MyBullet
to a target MyTarget
I have tried o add in this script the follow code
function OnCollisionEnter(collision: Collision) {
for (var contact: ContactPoint in collision.contacts) {
if(collision.gameObject.name=="MyTarget" || collision.gameObject.tag=="MyTarget" )
{
Debug.Log("Ball hit Box");
points++;
speed=bullet.velocity;
}
}
}
And nothing happens
I have altso tried to create in Start
function
var target=GameObject.FindGameObjectWithTag("MyTarget");
targetCollider=target.GetComponent.<CapsuleCollider>();
adding this check in Update
function
if(boatCollider.isTrigger){
Debug.Log("Ball hit Box");
points++;
speed=bullet.velocity;
}
With no result. How could I fix this?
Please note that this script is not attached to MyTarget
object is attached to my GUI canvas object
Answer by Hellium · Jun 30, 2015 at 06:39 PM
Making some research before asking a question is always a good idea :
Check OnCollisionEnter on other GameObject
http://answers.unity3d.com/questions/519708/check-oncollisionenter-on-other-gameobject.html
Note that the FAQ mentions it :
Please look around to see if your question has already been asked (and maybe even answered!) before you ask.
Then, you know what you have to do !
Could you help me to understand what is wrong with my code? If I have asked the question is because I haven't found the solution searching in official documentation
I think the documentation is quite clear about this :
OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider
Thus, if you attach the code above on your GUI canvas, OnCollisionEnter will be called only if something has hit its collider.
If you want to detect if your object has hit something you must attach a script on your bullets with the OnCollisionEnter defined. There is no workaround.