首页 > 解决方案 > Unity 场景更改

问题描述

我试图在所有敌人都被击败后改变场景,这就是我目前所拥有的

public class areOpponentsDead : MonoBehaviour
{
    List<GameObject> listOfOpponents = new List<GameObject>();

    void Start()
    {
        listOfOpponents.AddRange(GameObject.FindGameObjectsWithTag("Enemy"));
        print(listOfOpponents.Count);
    }

    public void KilledOpponent(GameObject enemy)
    {
        if(listOfOpponents.Contains(opponent))
        {
            listOfOpponents.Remove(opponent);
        }

        print(listOfOpponents.Count);
    }

    public bool AreOpponentsDead()
    {
        if(listOfOpponents.Count <= 0)
        {
            Application.LoadScene("Level2");
        }
    }
}

我不知道是否应该将其链接到现有脚本或制作新脚本以及如何将其连接到游戏。

标签: c#unity3d

解决方案


我在我的 1 款游戏中加入了这个功能,每次有敌人死亡时,我的敌人脚本都会执行一次检查。该函数看起来像:

void Die()
    {
        Destroy(gameObject);
        if (gameManager != null)
        {
            if (gameManager.GetEnemies - 1 == 0)
            {
                gameManager.Invoke("WinLevel", 1f);
            }
        }
    }

使用游戏管理器来管理游戏是一种常见的做法,所以在这里,我的gameManager脚本在函数中跟踪游戏中敌人的数量GetEnemies。它也只有负责改变场景才有意义(在WinLevel我的例子中是函数)。此脚本附加到游戏管理器对象。

然后,您可以:

  1. 在敌人脚本中引用游戏管理器或...
  2. 制作脚本的静态实例

编辑: GameManager 脚本具有以下代码:

public class GameManager : MonoBehaviour
{
    // The integer is the index for the current scene and the string is the name of the scene
    public string nextLevel = "2";
    public int levelToUnlock = 2;

    public GameObject winMenu;
    public GameObject gameplayUI;
    public GameObject backgroundMusic;
    GameObject player;
    Rigidbody2D playerRigidbody2D;
    public AudioClip winMusic;
    public int GetEnemies { get { return GameObject.FindGameObjectsWithTag("Enemy").Length; } }
    private void Start()
    {
        GoogleMobileAdsDemoScript._Adins.DestroyBanner();
    }
    public void WinLevel()
    {
        GoogleMobileAdsDemoScript._Adins.ShowBannerAd();
        player = GameObject.FindGameObjectWithTag("Player");
        playerRigidbody2D = player.GetComponent<Rigidbody2D>();
        playerRigidbody2D.simulated = false;
        PlayerPrefs.SetInt("levelReached", levelToUnlock);
        winMenu.SetActive(true);
        gameplayUI.SetActive(false);
        backgroundMusic.GetComponent<AudioSource>().Stop();
        backgroundMusic.GetComponent<AudioSource>().PlayOneShot(winMusic);
    }
    public void NextLevel()
    {
        GoogleMobileAdsDemoScript._Adins.DestroyBanner();
        SceneManager.LoadScene(nextLevel);
    }
    public void RestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

推荐阅读