Load a weakly-referenced scene at runtime
Unity doesn't automatically load weakly-referenced scenes. This means you can't use 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 RuntimeUntypedWeakReferenceId
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;
}
}
}
}