我目前正在尝试以给定的速率实例化游戏对象。通常,InvokeRepeating可以完成此任务,但这次我不希望实例化对象时速率保持恒定。

我了解应该在代码的Start()部分内部调用InvokeRepeating。所以我的问题是:有什么办法可以解决这个问题,还是我必须采取其他方法?

谢谢大家!

这部分代码说明了我正在谈论的问题:

using UnityEngine;
using System.Collections;

public class InstantiateLARSpider : MonoBehaviour {

public float instantiateRate;
public GameObject xSpider;
private Vector3 position;
public float minimumSpeed;

void Start () {

    // instantiateRate is a variable that I want to modify over time.
    InvokeRepeating("NewSpider", 1.0f, instantiateRate);
}

void NewSpider ()
{
    position = new Vector3(transform.position.x, Random.Range(-4.5f,4.5f), 0);
    Debug.Log("Instantiated");
    var Spider = Instantiate(xSpider, position, Quaternion.identity) as GameObject;
    if(transform.position.x>=11.0f){
        Spider.rigidbody2D.velocity = new Vector2(-1.0f * Random.Range(minimumSpeed, 6.0f), 0.0f);
    }
    else if(transform.position.x<=-11.0f){
        Spider.rigidbody2D.velocity = new Vector2(1.0f * Random.Range(minimumSpeed, 6.0f), 0.0f);
    }
    //I was thinking about increasing the instantiateRate by 0.1 every time a Spider is instantiated.
    instantiateRate -= 0.1f;
    minimumSpeed += 0.1f;
}


}

最佳答案

在这种情况下,在用于调用InvokeRepeating之后更改InstantiateRate实际上不会更改InvokeRepeating接收到的参数的副本。要镜像InvokeRepeating的功能,您可能会得到类似于以下内容的结果:

    public delegate void MethodToCall(); //A delegate - you can pass in any method with the signature void xxx() in this case!
    public IEnumerator InvokeRepeatingRange(MethodToCall method, float timeUntilStart, float minTime, float maxTime)
    {
        yield return new WaitForSeconds(timeUntilStart);
        while (true)
        {
            method(); //This calls the method you passed in
            yield return new WaitForSeconds(Random.Range(minTime, maxTime))
        }
    }


我在这台计算机上没有Unity,因此无法验证它是否可以编译(主要是Random.Range部分,其余部分我都很熟悉)。在这种情况下,您称呼它的方式是:

    void Start()
    {
        StartCoroutine(InvokeRepeatingRange(NewSpider, 2, 5, 10));
    }

    void NewSpider() //Since NewSpider matches the signature void xxx(), we can pass it to InvokeRepeatingRange()
    {
        //...
    }


调整InvokeRepeatingRange内部的参数和逻辑以获得所需的效果,也许:

    public delegate void MethodToCall();
    public IEnumerator InvokeRepeatingDecreasingTime(MethodToCall method, float timeUntilStart, float minTime, float maxTime)
    {
        float currentTime = maxTime;
        yield return new WaitForSeconds(timeUntilStart);
        while (currentTime >= minTime)
        {
            method();
            currentTime -= .1f;
            yield return new WaitForSeconds(currentTime);
        }
    }


希望这为您提供了一种思考这种工作方式的新方法,并且也可以回答您的原始问题。

编辑:更新了更好的变量名称和更多的解释。
      如注释中所述添加了StartCoroutine()调用!

10-08 00:27