Enemy AI for top down shooter

I have a top-down shooter where the player can move freely in the screen. I want to add enemy AI in a way that when the enemy is off the screen, he needs to follow the player and once he’s inside, movement should be randomised.
I know I could use Vector3.MoveTowards() to get the enemy follow the player, but how do I know if he’s inside or outside the camera? I tried using OnBecameInvisible() and OnBecameVisible() triggers but the enemy keeps moving away from the player.
What am I missing here or is there any other approach to solve this?

Just a suggestion, but an alternative is to create a radius using colliders.

So you could code something like when the enemy enters the 2Dcollider he has random movement, and when he leaves he moves towards the player.

See these links for reference:

  1. https://stackoverflow.com/
  2. Unity - Scripting API: Collider2D.OnTriggerEnter2D(Collider2D)
  3. Unity - Scripting API: Collider2D.OnTriggerExit2D(Collider2D)

Hi, @Roy9720! You can create coroutine for each enemy, where you check every second, if enemy is on screen or not. You can check it by transform enemy world position to screen position

Camera.main.WorldToScreenPoint(transform.position);

Unity - Scripting API: Camera.WorldToScreenPoint

I used the Camera.main.WorldToViewportPoint() and it worked, thanks for the answer.