c# - 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");
}
}
}
我不知道是否应该将其链接到现有脚本或制作新脚本以及如何将其连接到游戏。
解决方案
我在我的 1 款游戏中加入了这个功能,每次有敌人死亡时,我的敌人脚本都会执行一次检查。该函数看起来像:
void Die()
{
Destroy(gameObject);
if (gameManager != null)
{
if (gameManager.GetEnemies - 1 == 0)
{
gameManager.Invoke("WinLevel", 1f);
}
}
}
使用游戏管理器来管理游戏是一种常见的做法,所以在这里,我的gameManager
脚本在函数中跟踪游戏中敌人的数量GetEnemies
。它也只有负责改变场景才有意义(在WinLevel
我的例子中是函数)。此脚本附加到游戏管理器对象。
然后,您可以:
- 在敌人脚本中引用游戏管理器或...
- 制作脚本的静态实例
编辑: 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);
}
}
推荐阅读
- java - 在 WebView 中隐藏特定页面的键盘
- node.js - 在 readdir 中使用 readdir 后如何向客户端发送数据
- php - 无法在php中运行函数
- android - AndroidStudio Build 选项卡没有指向文件和行的链接?
- android-studio - 更新 Android Studio 和 Gradle 后 Gradle 项目同步失败
- c# - 在日期选择器中显示日期时间
- mysql - 错误:“列 'date_created' 不能为空”尝试创建实体时
- javascript - 我们如何发送一个隐藏在 php 中的 jquery 金额以供另一个页面检索金额值?
- performance - O*(c^n) 代表什么?它与 log * 有什么关系吗?(如果是这样 - 如何?)
- sql - Presto SQL 窗口聚合回顾 x 小时/分钟/秒