Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

I need somebody to help me with this line of code

A topic by Untiited123 created Apr 29, 2023 Views: 104 Replies: 2
Viewing posts 1 to 3

I am trying to make things spawn   randomly on the screen but there's an error and I can't troubleshoot it here's my line of code"

using UnityEngine;

public class Spawn : MonoBehaviour

{

    public GameObject objectToSpawn;

    public float spawnFrequency = 1f;

    public float spawnPadding = 0.1f;

    public int maxObjectsOnScreen = 5;

    private float nextSpawnTime = 0f;

    private int objectsOnScreen = 0;

    void Start()

    {

        // Set the initial spawn time to be now

        nextSpawnTime = Time.time;

    }

    void Update()

    {

        // Check if it's time to spawn a new object and if we haven't reached the max objects on screen

        if (Time.time >= nextSpawnTime && objectsOnScreen < maxObjectsOnScreen)

        {

            // Generate a random position within the camera view

            float x = Random.Range(Camera.main.ViewportToWorldPoint(Vector3.zero).x + spawnPadding, Camera.main.ViewportToWorldPoint(Vector3.right).x - spawnPadding);

            float y = Random.Range(Camera.main.ViewportToWorldPoint(Vector3.zero).y + spawnPadding, Camera.main.ViewportToWorldPoint(Vector3.up).y - spawnPadding);

            Vector3 spawnPosition = new Vector3(x, y, 0f);

            // Spawn a new object at the random position

            GameObject newObject = Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);

            objectsOnScreen++;

            // Update the next spawn time

            nextSpawnTime = Time.time + spawnFrequency;

        }

    }

    public void ObjectDestroyed()

    {

        objectsOnScreen--;

    }

}

"

pls help me

I came late