'How can I prevent a world click when unity button is clicked

First experimental project to understand working with Unity.

What I have now is that I create a grid and a "ground cube" with a scale of ((gridWidthcellSize),0.1f,(gridHeightcellSize)).

When clicking the mouse button somewhere on the grid I place a cube on the touched griCell

        if (Input.GetMouseButtonDown(0) && gameGrid.mouseGrid(out ix))
        {
            GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            go.transform.localScale = new Vector3(cellSize,10,cellSize);
            go.GetComponent<Renderer>().material.color = Color.magenta;
            go.name = "C " + ix.x + " " + ix.y;
            gameGrid.placeObject(ix,go);
        }

Where gameGrid.mouseGrid(out ix) returns the gridindex of the mouse using a ray.

    public bool mouseGrid(out Vector2Int v)
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit raycastHit, Mathf.Infinity)) 
        {
            v = worldposGrid(raycastHit.point);
            return true;
        }
        v = new Vector2Int();
        return false;
    }

And gameGrid.placeObject(ix,go); adds the gameobject to the world;

    public int placeObject(Vector2Int v, GameObject g)
    {
        g.transform.position = gridWorldpos(v) + new Vector3(0,gridCells[v.x,v.y].currentHeight,0);
        Debug.Log("PO "+ g.name + (gridWorldpos(v) + new Vector3(0,gridCells[v.x,v.y].currentHeight,0)) );
        gridCells[v.x,v.y].numObjects++;
        gridCells[v.x,v.y].currentHeight += g.transform.localScale.y;
        return gridCells[v.x,v.y].numObjects;
    }

This all works as expted.

Now I want to add a button to the screen, f.e. to decide what kind of object to place on the grid.

Created a canvas, added a button and linked the onClick to a GameManager method.

    public void buttonClicked(string s)
    {
        Debug.Log("BC " + s);
    }

The buttonClicked is correctly triggered with leftMouse clickt.

But.. when, on the screen, the button is on top of the grid, not only the buttonClicked() is executed, also the placeObject is executed. What I wanted/expected is that when clicking the button, only button click is done.

Can't find anything on how to achieve that. Anyone knows how to do it or have a link to an example ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source