[英]How can I generate enemies in random time (same position) in Unity 3D using C#?
我每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替换为该值即可:
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);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.