Andy Simpson

Andy Sim [Dev]

Blockchain Development

Blockchain Development

Game & App Development

Game & App Development

Website & Ecommerce Development

Website & Ecommerce Development

Game Art

Previous
Next

Game Animation

Custom Code/Scripts

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

public class SpawnerRandom : MonoBehaviour
{
    public static SpawnerRandom SharedInstance;
    public List<GameObject> pooledObjects;
    public List<GameObject> objectsToPool;
    public int amountToPool; //Amount of objects that will be pooled
    public int pooledAmount; //Amount of objects in pool

    public float maxTime = 50; //Maximum spawn time
    public float minTime = 10; //Minimum spawn time
    private float time; //Current time
    private float spawnTime; //Time to spawn object

    void Start()
    {
        SetRandomTime(); //Set random spawn time
        time = 0; //Set time to 0 on start

        pooledObjects = new List<GameObject>(); //Create pooled objects list
        for (int i = 0; i < amountToPool; i++)
        {
            int poolIndex = Random.Range(0, objectsToPool.Count);
            GameObject obj = (GameObject)Instantiate((objectsToPool[poolIndex]));
            obj.SetActive(false);
            pooledObjects.Add(obj);
        }
    }

    //Sets the random time between minTime and maxTime
    void SetRandomTime()
    {
        spawnTime = Random.Range(minTime, maxTime);
        //Debug.Log("Next object spawn in " + spawnTime + " seconds.");
    }

    void FixedUpdate()
    {
        //Counts up
        time += Time.deltaTime;
        //Check if its the right time to spawn the object
        if (time >= spawnTime)
        {
            SpawnObject();
            SetRandomTime();
            time = 0;
        }
    }
    
    //Pull object from object pool
    public GameObject GetPooledObject()
    {
        for (int i = 0; i < pooledObjects.Count; i++)
        {
            if (!pooledObjects[i].activeInHierarchy)
            {
                return pooledObjects[i];
            }
        }
        return null;
    }
    
    //Spawn Object from pool
    public void SpawnObject()
    {
        GameObject objectsToPool = GetPooledObject();
        if (objectsToPool != null)
        {
            objectsToPool.transform.position = gameObject.transform.position;
            objectsToPool.SetActive(true);
        }
    }
}
				
			

Testimonials