【问题标题】:Unity Scene ChangeUnity 场景更改
【发布时间】:2020-07-02 21:16:46
【问题描述】:

我正在尝试在所有敌人都被击败后改变场景,这是我目前所做的

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】:

我在我的 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多