Wednesday, May 30, 2018

unity - (2D) Detect mouse click on object with no script attached


I'm creating a 2D project which does not have a character. So i created an empty gameobject and attached the script to it. In the script, i have declared other objects which are in the scene like this:


public GameObject obj1,obj2,obj3;


How can I know if obj1 or obj2 or obj3 was clicked? Is raycasting the only solution?



Answer



Yes, you can use raycasting to detect the objects in your scene. You don't need to attach a custom script to the game objects you want to detect, but you do need to attach colliders to them.


In the update method of your script, attached to the otherwise empty object, you can check for when the mouse button is pressed. Then, cast a ray into the scene from the camera, through the mouse. Something like the following:


void Update() {
if (Input.GetMouseButtonDown(0)) {
Debug.Log("Pressed left click, casting ray.");
CastRay();
}

}

void CastRay() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100)) {
Debug.DrawLine(ray.origin, hit.point);
Debug.Log("Hit object: " + hit.collider.gameobject.name);
}
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...