如何使用C#在Unity 3D中的随机时间(相同位置)生成敌人?

fed*_*eno 2 c# game-development game-engine unity-game-engine

我每个人都反复产生敌人1.75f。但是我不知道如何使用随机函数。我的原型游戏就像Chrome浏览器中的游戏,当找不到页面时就会显示。

感谢你们对我的帮助。

这是我的代码:

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

    public class EnemyGeneratorController : MonoBehaviour
    {
        public GameObject enemyPrefeb;
        public float generatorTimer = 1.75f;

        void Start () 
        {

    }

    void Update ()
    {

    }

    void CreateEnemy()
    {
        Instantiate (enemyPrefeb, transform.position, Quaternion.identity);
    }

    public void StartGenerator()
    {
        InvokeRepeating ("CreateEnemy", 0f, generatorTimer);
    }

    public void CancelGenerator(bool clean = false)
    {
        CancelInvoke ("CreateEnemy");
        if (clean)
        {
            Object[] allEnemies = GameObject.FindGameObjectsWithTag ("Enemy");
            foreach (GameObject enemy in allEnemies)
            {
                Destroy(enemy);
            }
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

cax*_*xac 5

您可以使用StartCoroutine进行简单的敌人实例化:

using System.Collections;
Run Code Online (Sandbox Code Playgroud)

...

private IEnumerator EnemyGenerator()
{
    while (true)
    {
        Vector3 randPosition = transform.position + (Vector3.up * Random.value); //Example of randomizing
        Instantiate (enemyPrefeb, randPosition, Quaternion.identity);
        yield return new WaitForSeconds(generatorTimer);
    }
}

public void StartGenerator()
{
    StartCoroutine(EnemyGenerator());
}

public void StopGenerator()
{
    StopAllCoroutines();
}
Run Code Online (Sandbox Code Playgroud)

而且,正如Andrew Meservy所说,如果您想为计时器添加随机性(例如,使生成延迟从0.5秒随机变化到2.0秒),则可以只将yield return替换为以下内容:

yield return new WaitForSeconds(Mathf.Lerp(0.5f, 2.0f, Random.value));
Run Code Online (Sandbox Code Playgroud)

  • 由于OP想要一个随机时间,所以只需用Random.value替换generatorTimer,您就会得到我认为的答案。 (4认同)