在我的统一游戏(c#)中所有对象都被销毁后,我正在尝试加载下一个级别

问题描述 投票:0回答:1

我对编码真的很陌生,而且我几乎有一个游戏,底部有一门大炮,可以射击上面的移动平台。我需要做到这一点,以便在所有平台都被摧毁后加载下一个级别。代码的顶部部分很好。我有可以射击并摧毁平台的大炮。但我无法让 Unity 将已被破坏的平台数量注册为增加,以便我可以设置加载下一个级别的条件。

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

public class bullet : MonoBehaviour
{
    public float speed = 5f;
    public Rigidbody2D rb;
    public int DestroyedPlatforms;

    // Start is called before the first frame update
    void Start()
    {
        rb.velocity = transform.up * speed;
    }
     // THIS PART BELOW IS THE PROBLEM
     public void OnTriggerEnter2D(Collider2D other)
     {
        if (other.gameObject.CompareTag("platform"))
        {
            Destroy(other.gameObject);
            DestroyedPlatforms++;
        }
     // THEN SOMEWHERE ELSE I WOULD CODE "IF # OF PLATFORMS DESTROYED = 3" OR HOWEVER MANY     IN THAT LEVEL, "LOAD THE NEXT LEVEL"
        }

它可以很好地破坏平台,但在检查器中,即使在平台被破坏之后,被破坏的平台数量变量仍保持为 0。

c# unity-game-engine
1个回答
0
投票

如果检查器中的值未更新,则可能是您没有看到实时更新。

您可以通过在 OnTriggerEnter2D 方法中添加调试日志语句来检查变量是否实际被更新,如下所示:

public void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag("platform"))
    {
        Destroy(other.gameObject);
        DestroyedPlatforms++;
        Debug.Log("Number of destroyed platforms: " + DestroyedPlatforms);
    }

    // Check for level completion condition here
}

要在销毁一定数量的平台后加载下一个级别,您可以在 OnTriggerEnter2D 方法中添加条件或创建一个单独的方法来检查条件。以下是如何实现这一点的示例:

public void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag("platform"))
    {
        Destroy(other.gameObject);
        DestroyedPlatforms++;

        if (DestroyedPlatforms >= 3) // Change 3 to the number of platforms required to load the next level
        {
            LoadNextLevel();
        }
    }
}

private void LoadNextLevel()
{
    // Add code here to load the next level
    Debug.Log("Next level loaded!");
}
© www.soinside.com 2019 - 2024. All rights reserved.