How to make an enemy shoot only at visible player

I’ve seen similar questions but none of the answers have worked for me
So I have a top-down 2d shooter game

Currently, my Enemies are shooting at the player right from the start. However, these players are behind cover. So I would want them only to shoot when there is no cover between them and the player. How can I implement this? I’ve seen some ideas for making a 2d Raycast but those didn’t work for me as they just stopped the enemies from shooting in general

Here is a screenshot of my Unity window and the EnemyShooting code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyShooting : MonoBehaviour
{
    public GameObject EnemyBullet;
    public GameObject player;
    public Transform bulletPos;
    public float bulletSpeed = 2f;
    public float shootingRange = 10f;

    private float timer;
    

    void Update()
    {
    
        timer += Time.deltaTime;

        if (timer > 0.5 && Player.Alive)
        {
            timer = 0;
            EnemyShoot();
        }
        
    }
    void EnemyShoot()
    {
        GameObject bullet = Instantiate(EnemyBullet, bulletPos.position, bulletPos.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(bulletPos.up * bulletSpeed, ForceMode2D.Impulse);
    }
}

In this picture, the border of the roads has colliders therefore the enemies behind them shoot at me.

Hi @Samppav Yes, a raycast is going to be a good solution. Without seeing your raycast code, there’s no real way to determine why it kept the enemy from shooting at all. So, here’s some basic questions to answer regarding raycasting which can help fine tune the issue:

  • Is the raycast starting in the right place, aka at the enemies position?

  • Is the raycast in fact pointing at the player?

  • Does the raycast have enough distance to actually hit the player?

  • Have you validated these things by using Debug.DrawRay?

  • Have you validated the layermask is set?

  • Is the layermask correct, in that its able to hit both the player and the objects which can cause the enemy to lose line-of-sight?

  • Have you validated what the raycast is actually hitting?