- Home /
Detect collision if
What im trying to accomplish is: When I click my mouse I want to detect if two colliders in my game are touching and if they are i want it to do something. what am i doing wrong?
using UnityEngine;
using System.Collections;
public class Thetrigger : MonoBehaviour {
public GameObject MyCollider;
void OnCollisionStay(Collision collisionInfo){
if (Input.GetMouseButtonDown (0)){
if (collisionInfo.gameObject.name == "MyCollider")
Debug.Log ("it works");}
}
}
Thank you
$$anonymous$$ake sure both objects have colliders and if one of the object should have a non kinematic rigid body attached.
they both have colliders and one have a rigidbody still doesnt work
Answer by hav_ngs_ru · Feb 03, 2015 at 10:05 AM
collision is fery fast thing, it could be that you dont have a time to click mouse while colliders are touching..
Try use Input.GetMouseButton instead - it works not only when you click but also when you hold button - it makes yuo more easy to catch a moment (just press it right before colliders should touch).
And to avoid multiple-events, make some Lock flag (set it true in OnMouseButtonDown, and set to false in OnMouseButtonUp and in "mouse pressed && OnCollisionEnter" event was handler.
PS Or you could make it vice-versa: continous collision (fire flag in OnCollisionEnter + run "hold-collision" timer in OnCollisionExit, like Invoke("FunctionThatSetsollisionFlagToFalse", 1f), and simple instamt mouse event, like this if(Input.GetMouseButtonDown() && collisionFlag) {...}
in this case player should press mouse at the collision moment or a little later, that is more intuitiveю
what do you mean by Lock Flag? or the term flag in general?