using UnityEngine;

public class SpawnFromTop : MonoBehaviour
{
    [Header("Spawn Settings")]
    public GameObject prefab;
    public float spawnInterval = 1f;

    private Camera cam;

    void Start()
    {
        cam = Camera.main;
        InvokeRepeating(nameof(SpawnObject), 0f, spawnInterval);
    }

    void SpawnObject()
    {
        // Get top of the screen in world units
        Vector3 top = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2f, Screen.height, 10f));

        // Random X between left and right screen limits
        Vector3 left = cam.ScreenToWorldPoint(new Vector3(0, Screen.height, 10f));
        Vector3 right = cam.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 10f));

        float randomX = Random.Range(left.x, right.x);

        Vector3 spawnPos = new Vector3(randomX, top.y, 0f);

        Instantiate(prefab, spawnPos, Quaternion.identity);
    }
}