SceneRef - Unity
January 10, 2026•394 words
Unity SceneRef
Welcome to this article, where I will present a simple way to have scene references directly as a property in Unity.
The GitLab snippet with the code is right here.
SceneRef is a struct that contains the build index Unity uses to load a scene, which is more optimized at runtime. The GUID is kept as a string only for the editor, to keep track of the scene asset. Using a GUID allows the reference to persist even if the asset is renamed, moved, or deleted.
Keeping the index of a reference valid across modifications is complicated and can’t be perfect because of many constraints. My solution tries to auto‑fix the index when SceneRef is serialized or deserialized, but Unity’s AssetDatabase isn’t always available, causing the warning message you may see. In any case, it will track the build index, warn you if the scene isn’t indexed, and let you add it to the build index with a single button.
Managing the Build Index for Scenes
You can access the EditorBuildSettings in the editor, which lets you check whether a scene is referenced:
/// <summary>
/// Checks if the scene is in the build index.
/// </summary>
private bool IsSceneInBuildIndex(SceneAsset sceneAsset)
{
var path = AssetDatabase.GetAssetPath(sceneAsset);
var scenes = EditorBuildSettings.scenes;
foreach (var scene in scenes)
{
if (scene.path == path)
{
return true;
}
}
return false;
}
The following code retrieves the build index of a scene:
/// <summary>
/// Finds the build index of the scene
/// or returns -1 if not found.
/// </summary>
private int GetSceneBuildIndex(SceneAsset sceneAsset)
{
var path = AssetDatabase.GetAssetPath(sceneAsset);
var scenes = EditorBuildSettings.scenes;
for (var i = 0; i < scenes.Length; i++)
{
if (scenes[i].path == path)
{
return i;
}
}
return -1;
}
Finally, this code adds a scene to the build index:
List<EditorBuildSettingsScene> scenes = new();
scenes.AddRange(EditorBuildSettings.scenes);
if (GUID.TryParse(property.FindPropertyRelative(SceneGuidProperty).stringValue, out var guid))
{
scenes.Add(new EditorBuildSettingsScene
{
guid = guid,
enabled = true
});
Debug.Log($"Added scene '{AssetDatabase.GUIDToAssetPath(guid)}' to build index.");
}
EditorBuildSettings.scenes = scenes.ToArray();
How to use
Once you did setup the code in your project.
You just have to expose the SceneRef struct as a property, and can load a Scene:
[Tooltip("Next scene to load when the player escape.")]
[SerializeField] private SceneRef nextScene;
private void LoadNextScene() {
if (nextScene.IsBuildIndexValid())
nextScene.Load();
}