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

Unity预制体实例化与销毁问题:随机生成平台无法销毁

Unity平台跳跃游戏:平台销毁问题解决方案

你的代码存在的核心问题:

  • instance变量仅保存了最后一个生成的平台,前面生成的所有平台都没有被记录,导致FixedUpdate里只能检查最后一个平台,其他平台永远不会被销毁。
  • 判断销毁条件时用了platform.transform.position.y,这是预制体本身的位置,不是生成出来的实例的位置,逻辑完全错误。
  • 销毁边界的逻辑不合理,screenBounds.y *5这个值过大,且没有对应到"平台离开相机视野"的实际需求。

修改后的完整代码:

public GameObject platform;
private Vector2 screenBounds;
// 用List存储所有生成的平台实例,方便统一管理
private List<GameObject> platformInstances = new List<GameObject>();
// 需在Inspector面板中设置平台生成数量
public int platformCount = 5;

void Start()
{
    Vector2 spawnPosition = new Vector2();
    for (int i = 0; i < platformCount; i++)
    {
        spawnPosition.y = Random.Range(1f, 10f);
        spawnPosition.x = Random.Range(-2.0f, 2.0f);
        GameObject newPlatform = Instantiate(platform, spawnPosition, Quaternion.identity);
        // 将每个新生成的平台加入List
        platformInstances.Add(newPlatform);
    }
    // 正确获取屏幕世界坐标边界(z值取相机到世界的距离绝对值)
    screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Mathf.Abs(Camera.main.transform.position.z)));
}

void FixedUpdate()
{
    // 倒序遍历List,避免删除元素时索引错乱
    for (int i = platformInstances.Count - 1; i >= 0; i--)
    {
        GameObject currentPlatform = platformInstances[i];
        if (currentPlatform != null)
        {
            // 当平台移动到屏幕下边界之外时销毁(可根据游戏视角调整偏移量)
            if (currentPlatform.transform.position.y < screenBounds.y * -1 - 1)
            {
                Destroy(currentPlatform);
                // 从List中移除已销毁的平台引用
                platformInstances.RemoveAt(i);
            }
        }
        else
        {
            // 移除已被意外销毁的平台引用
            platformInstances.RemoveAt(i);
        }
    }
}

关键修改说明:

  • 使用List<GameObject>存储所有平台实例,确保每个生成的平台都能被检查和销毁。
  • 倒序遍历List:正序遍历删除元素会导致后续元素索引偏移,漏检平台;倒序则不会有这个问题。
  • 修正边界判断:将条件改为平台超出屏幕下边界(根据你的游戏方向调整,若y值越大越靠下则反过来),加偏移量是为了确保平台完全离开视野后再销毁。
  • 记得在Unity Inspector面板中给platformCount设置具体数值,否则生成逻辑不会执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:25