首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Unity场景变化

Unity场景变化
EN

Stack Overflow用户
提问于 2020-04-07 16:53:40
回答 1查看 188关注 0票数 0

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

代码语言:javascript
运行
复制
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");
        }
    }
}

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

EN

回答 1

Stack Overflow用户

发布于 2020-04-07 23:29:17

我在我的一款游戏中加入了这个功能,每当有敌人死了,我的敌人脚本就会执行一次检查。该函数如下所示:

代码语言:javascript
运行
复制
void Die()
    {
        Destroy(gameObject);
        if (gameManager != null)
        {
            if (gameManager.GetEnemies - 1 == 0)
            {
                gameManager.Invoke("WinLevel", 1f);
            }
        }
    }

通常使用游戏管理器来管理您的游戏,因此在这里,我的gameManager脚本在函数GetEnemies中跟踪我的游戏中的敌人数量。它也只负责改变场景(在我的例子中是函数WinLevel )。并且该脚本被附加到游戏管理器对象。

然后,您可以:

  1. 在敌方脚本中引用游戏管理器或...
  2. 创建script

的静态实例

编辑: GameManager脚本包含以下代码:

代码语言:javascript
运行
复制
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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61076234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档