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

Unity中C#脚本计数器莫名加2而非加1的问题求助

问题描述

编写了一段用于检测墙体是否经过玩家并增加计数器的代码,但有时同一块chunk会被重复触发检测,导致计数器累加2次,怀疑是Unity的问题。

原代码
for (int i = 0; i < SpawnedChunks.Count; i++)
{   
    float playerX = Player.transform.position.x;
    float chunkX = SpawnedChunks[i].bot_wall.position.x;

    if (chunkX < playerX && chunkX > -4.5f && GameObject.Find("player"))
    {
        PassedChunks.Add(SpawnedChunks[i]);
        PointsCounter.PointsCount++ ;
    }
}
问题原因与解决方法

这不是Unity的问题,是代码逻辑存在漏洞:没有判断当前chunk是否已经被加入PassedChunks列表,导致每帧检测时只要位置条件满足,就会重复执行添加和计数操作。

修改后的代码

for (int i = 0; i < SpawnedChunks.Count; i++)
{   
    var currentChunk = SpawnedChunks[i];
    float playerX = Player.transform.position.x;
    float chunkX = currentChunk.bot_wall.position.x;

    // 调整判断顺序,先确认玩家存在,再检查位置,最后验证未记录过该chunk
    if (GameObject.Find("player") != null && chunkX < playerX && chunkX > -4.5f && !PassedChunks.Contains(currentChunk))
    {
        PassedChunks.Add(currentChunk);
        PointsCounter.PointsCount++ ;
    }
}

额外优化建议

  • 避免每帧调用GameObject.Find("player"),可以在脚本初始化时(比如Start或Awake方法)缓存玩家引用,减少性能消耗:
    private GameObject player;
    
    void Start()
    {
        player = GameObject.Find("player");
    }
    
    之后在判断条件里直接用player != null即可。
  • 如果SpawnedChunks会动态移除元素,记得同步清理PassedChunks中对应的chunk,避免不必要的内存占用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:32:08