[英]Unity3D C# level generating script not working as intended
基本上,我为 Unity 中的无尽奔跑游戏编写了这个关卡生成脚本。 问题是这些板的生成速度太快,任何移动设备都无法处理。 为了防止这种情况,我添加了这行代码:
yield return new WaitForSeconds(2);
但出于某种原因,我的脚本会尽可能快地生成板,而不是等待 2 秒。
我尝试切换评论该行,但无论我尝试什么都没有用。 任何人都可以看看吗?
这是完整的脚本:
using System.Collections.Generic;
using UnityEngine;
public class GenerateLevel : MonoBehaviour
{
public GameObject[] section;
public int zPos = 19;
public bool creatingSection = false;
public int secNum;
void Update()
{
if (creatingSection == false)
creatingSection = true;
StartCoroutine(GenerateSection());
}
IEnumerator GenerateSection()
{
secNum = Random.Range(0, 3);
Instantiate(section[secNum], new Vector3(0, 0, zPos), Quaternion.identity);
zPos += 38;
yield return new WaitForSeconds(2);
creatingSection = false;
}
}
这是一个典型的错字:没有大括号 ( { }
) 的if
仅适用于下一个表达式,因此您的
if (creatingSection == false)
creatingSection = true;
StartCoroutine(GenerateSection());
基本上读
if (creatingSection == false)
{
creatingSection = true;
}
StartCoroutine(GenerateSection());
这意味着您每帧都启动一个协程!
你想要的是
if (creatingSection == false)
{
creatingSection = true;
StartCoroutine(GenerateSection());
}
无论如何,与其冒险并在每一帧轮询检查一个标志,你更应该做的是有一个适当的方法来开始你的例程
public class GenerateLevel : MonoBehaviour
{
[Header("Assets")]
public GameObject[] section;
[Header("Settings")]
public int zPos = 19;
private bool isGenerating;
// This atttribute adds an entry to the context menu of this component
// in the Inspector so you can still run it from there for testing
// see https://docs.unity3d.com/ScriptReference/ContextMenu.html
[ContextMenu(nameof(StartGenerating))]
public void StartGenerating()
{
// also prevent multiple concurrent routines
if(isGenerating) return;
StartCoroutine(GenerateSection());
}
IEnumerator GenerateSection()
{
if(isGenerating) yield break;
isGenerating = true;
// I would go fully dynmic here and intad of hoping that there are 3 elements in "section"
// rather rely on its actual length
// => you can easily add and remove items via the Inspector and it still works without touching the code
var secNum = Random.Range(0, section.Length);
Instantiate(section[secNum], new Vector3(0, 0, zPos), Quaternion.identity);
zPos += 38;
yield return new WaitForSeconds(2);
isGenerating = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.