Detect touch over UI element

So, I am building a mobile game where you place blocks by touching the screen. The problem is, when I am touching the player controls, the game places a block. I have been working on this problem for about 2 days, but with little to no avail. Can somebody help me? I will provide the script I wrote. Thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class main : MonoBehaviour
{

public GameObject selected;
Camera cam;
public bool CanPlace=true;
public Vector3 mouseWorldPosition;
public int j = 0;
public Text txt;




public void Awake()
{
    cam = Camera.main;
}

void Update()
{

    txt.text = j.ToString();
  
    foreach (Touch touch in Input.touches)
    {
        int id = touch.fingerId;

        if (EventSystem.current.IsPointerOverGameObject(id))
        {
            j++;
            //StartCoroutine(waitForPlace());
        }
        else { j--;
            Instantiate(selected, mouseWorldPosition, Quaternion.identity);
        }
    } /*this is the part that checks if touch is over ui, it sometimes works and sometimes doesn't*/


    Vector3 worldPoint = Input.mousePosition;
    worldPoint.z = Mathf.Abs(cam.transform.position.z);
    //worldPoint.z = 11f;
    mouseWorldPosition = cam.ScreenToWorldPoint(worldPoint);
    mouseWorldPosition.z = 0f;
   
}

public IEnumerator waitForPlace()
{
    CanPlace = false;
    yield return new WaitForSeconds(0.2f);
    CanPlace = true;
}

}

call this function before spawning the block, this function return true when you hover over a UI.

private bool IsMouseOverUI()
{
return EventSystem.current.IsPointerOverGameObject();
}

Replace your code with this :-

void Update()
{

txt.text = j.ToString();

foreach (Touch touch in Input.touches)
{
    int id = touch.fingerId;

    if (EventSystem.current.IsPointerOverGameObject(id))
    {
        j++;
        //StartCoroutine(waitForPlace());
    }
    else { j--;
   if(!IsMouseOverUI)
   {
        Instantiate(selected, mouseWorldPosition, Quaternion.identity);
    }
   }
} /*this is the part that checks if touch is over ui, it sometimes works and sometimes doesn't*/


Vector3 worldPoint = Input.mousePosition;
worldPoint.z = Mathf.Abs(cam.transform.position.z);
//worldPoint.z = 11f;
mouseWorldPosition = cam.ScreenToWorldPoint(worldPoint);
mouseWorldPosition.z = 0f;

}