Make something happen when object is in view of Main Player Camera

I wanted to make a script in which something happens to the player whenever the enemy is in view of the player’s camera.

I was wondering if there is a simple way to make this happen because I haven’t found an answer online yet.

Any ideas?

Thank you.

In Unity, you can use the OnBecameVisible and OnBecameInvisible methods provided by the Renderer component to achieve this. These methods are called when a renderer becomes visible or invisible from the camera’s perspective.

Here’s an example code snippet that demonstrates how to use these methods:

using UnityEngine;

public class EnemyDetection : MonoBehaviour
{

    private void OnBecameVisible()
    {
        // Trigger an event or action when the enemy comes into view
        Debug.Log("Enemy came into view!");
        // Your code here
    }

    private void OnBecameInvisible()
    {
        // Trigger an event or action when the enemy goes out of view
        Debug.Log("Enemy went out of view!");
        // Your code here
    }
}

Attach this script to your enemy object. The OnBecameVisible method will be called when the enemy comes into view, and the OnBecameInvisible method will be called when it goes out of view.

Note that these methods only work when the enemy object has a Renderer component attached. If the enemy object doesn’t have a renderer, you’ll need to add one or use a different detection method.

Hope this helps!