- Home /
Question by
evannnc · Feb 16, 2016 at 01:00 PM ·
raycasting
raycast is returning object underneath another object
I'm trying to detect which game object the user has clicked, but the raycast is returning an object that is fully covered by another object. any clue how this is happening?
//get where the user clicked the mouse in world coordinates. Input.mousePosition returns a pixel coordinate
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);
if (hit.collider != null) {
Debug.Log ("confirm collision with " + hit.transform.gameObject.name);
switch (hit.transform.gameObject.name) {
// cancel X button pressed
case "confirmCancel":
Debug.Log ("this.gameobject= " + this.gameObject.name);
// get the upgrade script to enable the collion checking again
shopBg = (GameObject) GameObject.Instantiate(Resources.Load("shopBg"));
upgrade = shopBg.GetComponent<upgradeScript> ();
upgrade.confirmShown = false;
// remove this screen
GameObject.Destroy (this.gameObject);
break;
Comment
You probably forgot a collider on your object, the code seems fine.
Best Answer
Answer by Fredex8 · Feb 19, 2016 at 12:41 AM
Seems obvious enough but also easy enough mistake to make... check the object covering it isn't set to the Ignore Raycast layer and that it actually has a collider on it for the raycast to hit.
Your answer
Follow this Question
Related Questions
Set raycast on player camera or object? 0 Answers
Raycasts and new Gui buttons 0 Answers
Raycasting vs. events 0 Answers
Raycasting not working on all sides? 1 Answer
Raycast stops working for big scaled objects sometimes 2 Answers