制作Flappy Bird练习版:管道生成计时器代码报错求助
简易Flappy Bird管道生成脚本错误修复与优化
我正在制作简易版Flappy Bird用于练习,需求是按时间间隔生成管道,后续可缩短时间间隔逐步提升难度。以下是我的pipe_Spawner脚本代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class pipe_Spawner : MonoBehaviour { public GameObject pipesPrefab; // Start is called before the first frame update void Start() { } public float secsToNext -= Time.deltaTime// public lets you check it running in the inspector { // Update is called once per frame void Update()//every single frame its called { secsToNext -= Time.deltaTime; // T.dt is secs since last update if(secsToNext<=5) { secsToNext = Random.Range(8.0f, 12.0f); float Vertical = Random.Range(1.0f, 6.0f); float Horizontal = Random.Range(-7.0f, 7.0f); Instantiate(pipesPrefab, new Vector2(Vertical,Horizontal), Quaternion.identity); } } } }
当前Unity中出现以下编译错误:
- Assets\pipe_Spawner.cs(13,29): error CS1003: Syntax error, ',' expected
- Assets\pipe_Spawner.cs(13,32): error CS1002: ; expected
- Assets\pipe_Spawner.cs(14,5): error CS1519: Invalid token '{' in class, struct, or interface member declaration
- Assets\pipe_Spawner.cs(27,1): error CS1022: Type or namespace definition, or end-of-file expected
注:当前坐标为随机值仅用于测试。
错误分析与修复
- 变量声明错误:类成员位置不能直接对变量执行
-= Time.deltaTime操作,需先声明并初始化变量,再在方法内修改。 - 代码块嵌套错误:错误给变量声明添加了
{},导致Update方法被非法嵌套,同时末尾多了一个冗余的闭合}。 - 生成逻辑错误:原条件
secsToNext <=5会导致游戏启动就触发生成,不符合“间隔时间到了才生成”的逻辑,应改为secsToNext <=0。
修复后的代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class pipe_Spawner : MonoBehaviour { public GameObject pipesPrefab; // 初始生成间隔,可在Inspector面板调整 public float spawnInterval = 3f; // 距离下次生成的剩余时间 private float secsToNext; void Start() { // 初始化剩余时间为初始间隔 secsToNext = spawnInterval; } void Update() { secsToNext -= Time.deltaTime; // 剩余时间归零时生成管道 if(secsToNext <= 0) { // 重置剩余时间,加入随机范围增加游戏变化 secsToNext = Random.Range(2f, spawnInterval); // 测试用随机坐标,后续可改为固定X轴+随机Y轴(符合Flappy Bird经典逻辑) float verticalPos = Random.Range(1.0f, 6.0f); float horizontalPos = Random.Range(-7.0f, 7.0f); Instantiate(pipesPrefab, new Vector2(horizontalPos, verticalPos), Quaternion.identity); } } }
难度提升思路
后续要提升难度,只需在游戏过程中逐步减小spawnInterval的值即可,比如通过分数触发:
// 示例:每得10分缩短0.2秒间隔,最低限制为1秒避免过快 public void IncreaseDifficulty(int score) { if(score % 10 == 0 && spawnInterval > 1f) { spawnInterval -= 0.2f; } }
内容的提问来源于stack exchange,提问作者SirShrkimpalot
相关产品推荐
相关产品推荐

