How to make it so with 2 objects at the same transform.position, 1 is always over the other

Probably a pretty stupid question! Can post code if it really is necessary.

Basically I have a grid made of square GameObjects and I have code that snaps Ingredient objects of the same size to the exact location of the nearest grid square. To make it so only the Ingredient the mouse is over will be picked up, I have a bool mouseOver that goes true when OnMouseEnter and OnMouseStay call and goes false when OnMouseExit calls. This bool allows the Ingredient object to be picked up if true.

However, sometimes the Ingredient is unable to call OnMouseEnter or OnMouseStay because the game sees the grid square at the exact same location as on top of the Ingredient and blocks all of the OnMouse functions.

I’ve tried setting the Z of Ingredients forward and the Z of the grid spaces backward, but both of them mess up the OnMouse functions and the grid snapping. I’ve also tried playing around with the Sorting Layer and Order in Layer, but they only affect the visual layers. Both objects are at the same X, Y, and Z.

I am not sure of the logic used in those callbacks. But you might want to switch to doing raycasts your self.
You can then specify a layer and only detect objects on that layer.

1 Like

How would I go about doing this, if you don’t mind me asking? This is the code on the object that I want to be picked up. I’ve removed the things about the grid in the script because I don’t think they’re necessary towards what you’re saying I should do.

public class IngredientScript : MonoBehaviour {

    public bool pickedUp = false, mouseOver = false;

    void Update () {
        CheckMouse ();
    }

    void CheckMouse()                                    //checks the mouse button to determine what must be picked up or put down
    {
        if (Input.GetMouseButtonDown (0)) {                //if the mouse is over the ingredient, you CAN pick it up
            if (mouseOver) {
                pickedUp = true;
                }
            }
        }
        if (Input.GetMouseButton (0) && pickedUp) {        //if the mouse is held down, the ingredient will move
            PickUpIngredient ();
        }
        if (Input.GetMouseButtonUp (0) && pickedUp == true) {
            pickedUp = false;
        }
    }

    void PickUpIngredient()
    {
        Vector2 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        transform.position = pos;
    }

    void OnMouseEnter()
    {
        mouseOver = true;
    }

    void OnMouseOver()
    {
        mouseOver = true;
    }

    void OnMouseExit()
    {
        mouseOver = false;
    }
}