Alan Vieira Rezende
Alan Vieira Rezende

Reputation: 412

Set delay time to spawn object

I have the SpawnScript (Below) I want to create a function within the SPAWN, so I can put the minimum and maximum delay time that an object can be created by the inspector.

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

public class SpawnController : MonoBehaviour
{

    public float maxWidth;
    public float minWidth;

    public float minTime;
    public float maxTime;

    public float rateSpawn;
    private float currentRateSpawn;

    public GameObject tubePrefab;

    public int maxSpawnTubes;

    public List<GameObject> tubes;

    // Use this for initialization
    void Start ()
    {


        for (int i = 0; i < maxSpawnTubes; i++) {
            GameObject tempTube = Instantiate (tubePrefab) as GameObject;
            tubes.Add (tempTube);
            tempTube.SetActive (false);

        }

        currentRateSpawn = rateSpawn;

    }

    // Update is called once per frame
    void Update ()
    {

        currentRateSpawn += Time.deltaTime;
        if (currentRateSpawn > rateSpawn) {
            currentRateSpawn = 0;
            Spawn ();
        }
    }

    private void Spawn ()
    {

        float randWitdh = Random.Range (minWidth, maxWidth);

        GameObject tempTube = null;

        for (int i = 0; i < maxSpawnTubes; i++) {
            if (tubes [i].activeSelf == false) {
                tempTube = tubes [i];
                break;
            }
        }

        if (tempTube != null)
            tempTube.transform.position = new Vector3 (randWitdh, transform.position.y, transform.position.z);
        tempTube.SetActive (true);
    }
}

Upvotes: 0

Views: 1743

Answers (2)

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10551

InvokeRepeating Method is the way to deal with code repetation. You can call your Spawn method with invoke repeating inside of Start event and specify time according to your choice as invoke repeating define:

public void InvokeRepeating(string methodName, float time, float repeatRate);

Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.

something like this edit require in your script:

void Start(){
InvokeRepeating("Spawn",2, 0.3F);
}

Upvotes: 1

yes
yes

Reputation: 967

you could use Time.realtimeSinceStartup for timestamps - this kinda would fit the way you do it atm. or you use coroutines which is very unity and one better learns to use them early than late. or you use invoke which probably is the shortest way of doing it.

http://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.html http://docs.unity3d.com/Manual/Coroutines.html http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

edit: well actually you also could just rateSpawn = Random.Range(minTime, maxTime); inside the if statement in update, this would fit your current approach most.

Upvotes: 1

Related Questions