Mau*_*mbo 3 c# unity-game-engine scene-manager
加载新场景时,我遇到了鼠标拖动无法转移到下一个场景并且在加载新场景时必须重新单击的麻烦。
我希望鼠标点击可以无缝地转移到下一个场景而不会引起玩家的注意,更一般地说,我想知道如何最好地保留某些游戏对象并使它们转移到下一个场景。
从本质上讲,我想要做的是让整个游戏表现得像一个大场景,玩家可以玩这个大场景,但仍然可以分解成更小的场景,这些场景可以在后期访问或转换成关卡。
提前致谢。
这是我目前使用的代码
using UnityEngine;
using System.Collections;
using UnityEngine.Profiling;
public class MoveBall : MonoBehaviour
{
public static Vector2 mousePos = new Vector2();
private void OnMouseDrag()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePos;
DontDestroyOnLoad(this.gameObject);
}
}
Run Code Online (Sandbox Code Playgroud)
Bellow 是负责加载场景的脚本:
public class StarCollision : MonoBehaviour
{
private bool alreadyScored = false;
private void OnEnable()
{
alreadyScored = false;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("White Ball"))
{
if (!alreadyScored)
{
ScoreScript.scoreValue += 1;
StartCoroutine(ChangeColor());
alreadyScored = true;
}
}
if (ScoreScript.scoreValue > 4)
{
SceneManager.LoadScene(1);
}
}
private IEnumerator ChangeColor()
{
ScoreScript.score.color = Color.yellow;
yield return new WaitForSeconds(0.1f);
ScoreScript.score.color = Color.white;
gameObject.SetActive(false);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为它不起作用的主要原因是您可能Camera在新场景中还有另一个。
在OnMouseDrag依靠内部使用的对象的物理系统上Collider从和光线投射Camera。现在,如果您切换场景,我猜会禁用一个摄像头,因此您的拖动会中断。
还使用LoadScene而不是LoadSceneAsync导致明显的滞后,也可能与问题有关。
我有一个可能更复杂的解决方案,但这就是我通常做的:
这个场景包含诸如 MainCamera、全局光照、全局管理器组件之类的东西,无论如何都不应该被破坏。
你说你不希望你的用户在场景切换时不注意,所以我建议SceneManager.LoadSceneAsync无论如何使用。
然后为了不卸载前面提到的MainScene你传递可选参数 LoadSceneMode.Additive。这使得新场景被加载到已经存在的场景之外。然后,您只需通过卸载先前添加加载的场景来交换它们。
我static为此创建了一个非常简单的管理器:
public static class MySceneManager
{
// store build index of last loaded scene
// in order to unload it later
private static int lastLoadedScene = -1;
public static void LoadScene(int index, MonoBehaviour caller)
{
caller.StartCoroutine(loadNextScene(index));
}
// we need this to be a Coroutine (see link below)
// in order to correctly set the SceneManager.SetActiveScene(newScene);
// after the scene has finished loading. So the Coroutine is required
// in order to wait with it until the reight moment
private static IEnumerator loadNextScene(int index)
{
// start loading the new scene async and additive
var _async = SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
// optionally prevent the scene from being loaded instantly but e.g.
// display a loading progress
// (in your case not but for general purpose I added it)
_async.allowSceneActivation = false;
while (_async.progress < 0.9f)
{
// e.g. show progress of loading
// yield in a Coroutine means
// "pause" the execution here, render this frame
// and continue from here in the next frame
yield return null;
}
_async.allowSceneActivation = true;
// loads the remaining 10%
// (meaning it runs all the Awake and OnEnable etc methods)
while (!_async.isDone)
{
yield return null;
}
// at this moment the new Scene is supposed to be fully loaded
// Get the new scene
var newScene = SceneManager.GetSceneByBuildIndex(index);
// would return false if something went wrong during loading the scene
if (!newScene.IsValid()) yield break;
// Set the new scene active
// we need this later in order to place objects back into the correct scene
// if we do not want them to be DontDestroyOnLoad anymore
// (see explanation in SetDontDestroyOnLoad)
SceneManager.SetActiveScene(newScene);
// Unload the last loaded scene
if (lastLoadedScene >= 0) SceneManager.UnloadSceneAsync(lastLoadedScene);
// update the stored index
lastLoadedScene = index;
}
}
Run Code Online (Sandbox Code Playgroud)
这MySceneManager是一个static class所以它不附加到任何游戏对象或场景,而只是“生活”在Assets. 您现在可以使用任何地方调用它
MySceneManager.LoadScene(someIndex, theMonoBehaviourCallingIt);
Run Code Online (Sandbox Code Playgroud)
type 的第二个参数MonoBehaviour(基本上是您的脚本)是必需的,因为必须有人负责运行IEnumerator 协程,而协程static class本身无法完成。
目前,您正在添加您随时拖动的任何游戏对象DontDestroyOnLoad。但是您永远不会撤消此操作,因此您同时触及的任何内容都会从那一刻开始……永远。
我宁愿使用例如类似的东西
public static class GameObjectExtensions
{
public static void SetDontDestroyOnLoad(this GameObject gameObject, bool value)
{
if (value)
{
// Note in general if DontDestroyOnLoad is called on a child object
// the call basically bubbles up until the root object in the Scene
// and makes this entire root tree DontDestroyOnLoad
// so you might consider if you call this on a child object to first do
//gameObject.transform.SetParent(null);
UnityEngine.Object.DontDestroyOnLoad(gameObject);
}
else
{
// add a new temporal GameObject to the active scene
// therefore we needed to make sure before to set the
// SceneManager.activeScene correctly
var newGO = new GameObject();
// This moves the gameObject out of the DontdestroyOnLoad Scene
// back into the currently active scene
gameObject.transform.SetParent(newGO.transform, true);
// remove its parent and set it back to the root in the
// scene hierachy
gameObject.transform.SetParent(null, true);
// remove the temporal newGO GameObject
UnityEngine.Object.Destroy(newGO);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个扩展方法,它允许您简单地调用
someGameObject.SetDontDestroyOnLoad(boolvalue);
Run Code Online (Sandbox Code Playgroud)
在任何游戏对象引用上。
然后我把你的脚本改成了
public class MoveBall : MonoBehaviour
{
public static Vector2 mousePos = new Vector2();
// On mouse down enable DontDestroyOnLoad
private void OnMouseDown()
{
gameObject.SetDontDestroyOnLoad(true);
}
// Do your dragging part here
private void OnMouseDrag()
{
// NOTE: Your script didn't work for me
// in ScreenToWorldPoint you have to pass in a Vector3
// where the Z value equals the distance to the
// camera/display plane
mousePos = Camera.main.ScreenToWorldPoint(new Vector3(
Input.mousePosition.x,
Input.mousePosition.y,
transform.position.z)));
transform.position = mousePos;
}
// On mouse up disable DontDestroyOnLoad
private void OnMouseUp()
{
gameObject.SetDontDestroyOnLoad(false);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的StarCollision脚本中你只需要交换
SceneManager.LoadScene(1);
Run Code Online (Sandbox Code Playgroud)
和
MySceneManager.LoadScene(2, this);
Run Code Online (Sandbox Code Playgroud)
为了进行一点演示,我使用两个简单的脚本“伪造”了它
主场景中的这个
public class LoadFirstscene : MonoBehaviour
{
// Start is called before the first frame update
private void Start()
{
MySceneManager.LoadScene(1, this);
}
}
Run Code Online (Sandbox Code Playgroud)
而这个在其他场景中
public class LoadNextScene : MonoBehaviour
{
[SerializeField] private int nexSceneIndex;
private void Update()
{
if (!Input.GetKeyDown(KeyCode.Space)) return;
MySceneManager.LoadScene(nexSceneIndex, this);
}
}
Run Code Online (Sandbox Code Playgroud)
并有 3 个场景:
主要:如前所述包含
LoadFirstScene测试:包含
MoveBall“球体”LoadNextScene测试2:包含
LoadNextScene使用与构建设置匹配的索引(确保Main始终位于0;) )
我现在可以在钥匙之间切换test和test2使用Space。
如果我同时拖动一个对象,我可以将它带入下一个场景(但一次只能拖一个)。我什至可以将它再次带回第一个场景,以便拥有例如我可以玩的两个球体对象;)