Load a weakly-referenced scene at runtime
Unity doesn't automatically load weakly-referenced scenes. This means you can't use SceneManager APIs such as LoadScene to open the scene. Instead, you must use RuntimeContentManager APIs to load the scene from the content archive. To load a scene at runtime, you must have a weak reference to the scene stored in an ECS component. The weak reference can be either a WeakObjectSceneReference or an UntypedWeakReferenceId. For information on how to store a weak reference to an object, refer to Weakly reference a scene.
Load a scene at runtime with a WeakObjectSceneReference
The following code example shows how to use WeakObjectSceneReferences
to load scenes from an ISystem
. For information on how to pass a WeakObjectSceneReference
to a component, refer to Weakly reference a scene.
using Unity.Entities;
using Unity.Entities.Content;
public struct WeakObjectSceneReferenceData : IComponentData
{
public bool startedLoad;
public WeakObjectSceneReference scene;
}
[WorldSystemFilter(WorldSystemFilterFlags.Default | WorldSystemFilterFlags.Editor)]
[UpdateInGroup(typeof(PresentationSystemGroup))]
public partial struct LoadSceneFromWeakObjectReferenceSystem : ISystem
{
public void OnCreate(ref SystemState state) { }
public void OnDestroy(ref SystemState state) { }
public void OnUpdate(ref SystemState state)
{
foreach (var sceneData in SystemAPI.Query<RefRW<WeakObjectSceneReferenceData>>())
{
if (!sceneData.ValueRO.startedLoad)
{
sceneData.ValueRW.scene.LoadAsync(new Unity.Loading.ContentSceneParameters()
{
loadSceneMode = UnityEngine.SceneManagement.LoadSceneMode.Additive
});
sceneData.ValueRW.startedLoad = true;
}
}
}
}
Load a scene at runtime with an UntypedWeakReferenceId
The following code example shows how to use the RuntimeContentManager APIs and an UntypedWeakReferenceId
to load a scene from an ISystem
. For information on how to pass a UntypedWeakReferenceId
to a component, refer to Weakly reference an object from a C# script.
using Unity.Entities;
using Unity.Entities.Content;
using Unity.Entities.Serialization;
public struct SceneUntypedWeakReferenceIdData : IComponentData
{
public bool startedLoad;
public UntypedWeakReferenceId scene;
}
[WorldSystemFilter(WorldSystemFilterFlags.Default | WorldSystemFilterFlags.Editor)]
[UpdateInGroup(typeof(PresentationSystemGroup))]
public partial struct LoadSceneFromUntypedWeakReferenceIdSystem : ISystem
{
public void OnCreate(ref SystemState state) { }
public void OnDestroy(ref SystemState state) { }
public void OnUpdate(ref SystemState state)
{
foreach (var sceneData in SystemAPI.Query<RefRW<SceneUntypedWeakReferenceIdData>>())
{
if (!sceneData.ValueRO.startedLoad)
{
RuntimeContentManager.LoadSceneAsync(sceneData.ValueRO.scene,
new Unity.Loading.ContentSceneParameters()
{
loadSceneMode = UnityEngine.SceneManagement.LoadSceneMode.Additive
});
sceneData.ValueRW.startedLoad = true;
}
}
}
}