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

问题描述 投票:2回答:2

我反复生成每个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);
            }
        }   
    }
}
c# unity3d game-engine game-development
2个回答
5
投票

您可以使用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替换为这个:

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

1
投票

修改版本生成敌人

将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);
            }
        }   
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.