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



i每个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);
            }
        }   
    }
}

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

using System.Collections;

...

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

和,正如安德鲁·梅塞维(Andrew Meservy)所说,如果您想在计时器中添加随机性(例如,将产卵延迟从0.5秒随机到2.0秒),那么您可以将收益率替换为此:

yield return new WaitForSeconds(Mathf.Lerp(0.5f, 2.0f, Random.value));

修改版本以生成敌人

随机时间使用StartCoroutine

using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class EnemyGeneratorController : MonoBehaviour
    {
        public GameObject enemyPrefeb;
         public float generatorTimer { set; get; }
        void Start () 
        {

generatortimer = 1.75f;

    }
    void Update ()
    {
    }
    void IEnumerator CreateEnemy()
    {
        Instantiate (enemyPrefeb, transform.position, Quaternion.identity);
        yield return new WaitForSeconds(generatorTimer);
        generatorTimer = Random.Range(1f, 5f);
    }
    public void StartGenerator()
    {
        StartCoroutine(CreateEnemy());
    }
    public void CancelGenerator(bool clean = false)
    {
        CancelInvoke ("CreateEnemy");
        if (clean)
        {
            Object[] allEnemies = GameObject.FindGameObjectsWithTag ("Enemy");
            foreach (GameObject enemy in allEnemies)
            {
                Destroy(enemy);
            }
        }   
    }
}

最新更新