设置生成对象的延迟时间 [英] Set delay time to spawn object

查看:187
本文介绍了设置生成对象的延迟时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有SpawnScript(如下) 我想在SPAWN中创建一个函数,因此我可以设置检查器可以创建对象的最小和最大延迟时间.

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);
    }
}

推荐答案

InvokeRepeating 方法是处理代码重复的方法. 您可以通过在Start事件中进行重复调用来调用Spawn方法,并根据您的选择指定时间作为重复调用定义:

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

以秒为单位调用方法methodName,然后每隔一秒重复一次 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);
}

这篇关于设置生成对象的延迟时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆