簡體   English   中英

Unity 場景更改

[英]Unity Scene Change

我試圖在所有敵人都被擊敗后改變場景,這就是我目前所擁有的

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");
        }
    }
}

我不知道是否應該將其鏈接到現有腳本或制作新腳本以及如何將其連接到游戲。

我在我的 1 款游戲中加入了這個功能,每次有敵人死亡時,我的敵人腳本都會執行一次檢查。 function 看起來像:

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

使用游戲管理器來管理游戲是一種常見的做法,所以在這里,我的gameManager腳本在 function GetEnemies中跟蹤我的游戲中的敵人數量。 它也只有負責改變場景才有意義(在我的例子中是 function WinLevel )。 此腳本附加到游戲管理器 object。

然后,您可以:

  1. 在敵人腳本中引用游戲管理器或...
  2. 制作腳本的 static 實例

編輯: 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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM