You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity Flappy Bird复刻项目中deadZone变量异常变为1的问题

Flappy Bird复刻版:public变量deadZone运行时自动变为1的问题

我正在制作首个Unity项目——Flappy Bird复刻版。在编写管道移出画面后销毁的代码时遇到问题:我定义了public类型的float变量deadZone并赋值为-46,但运行游戏时该变量会变为1,请问这是什么原因?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PipeMovement : MonoBehaviour{
    public float moveSpeed = 1;
    public float deadZone = -46;

    // Start is called before the first frame update
    void Start(){
        
    }

    // Update is called once per frame
    void Update(){
        transform.position += (Vector3.left * moveSpeed) * Time.deltaTime;
        if (transform.position.x < deadZone){
            Destroy(gameObject);
        }
    }
}

这是Unity序列化机制导致的:public字段的代码默认值只会在脚本第一次挂载到物体上时生效,之后你在Inspector面板里对这个变量做的修改会被Unity永久保存,运行时会直接用Inspector里的数值覆盖代码里的默认值。

你大概率是之前选中挂载了PipeMovement的管道对象时,在Inspector里把deadZone改成了1,哪怕之后代码里改回-46,Unity还是会用Inspector里存储的1来运行。

解决方法很简单:

  • 选中对应的管道对象,在Inspector面板找到PipeMovement组件里的deadZone变量,手动把它改回-46;
  • 要是怕之后误改,可以点击变量旁边的小锁图标锁定数值;
  • 或者右键PipeMovement组件,选择「Reset」,这样所有变量都会恢复到代码里的默认值。

另外提一句:如果不想让Inspector修改这个变量,但又需要在面板里查看,把public改成private,再加上[SerializeField]标签,这样既不会被Inspector的修改覆盖代码默认值,又能在面板里看到变量状态。

内容的提问来源于stack exchange,提问作者Bcbc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:12:16