unity-atoms/Source/Types/SceneField.cs

64 lines
2.0 KiB
C#
Raw Normal View History

using System;
using UnityEngine;
using UnityEngine.SceneManagement;
2019-04-17 06:53:00 -04:00
#if UNITY_EDITOR
using UnityEditor;
#endif
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
2019-05-04 05:54:20 -04:00
namespace UnityAtoms
{
[Serializable]
public struct SceneField : ISerializationCallbackReceiver
{
2019-05-04 05:54:20 -04:00
[SerializeField] private Object _sceneAsset;
[SerializeField] private string _sceneName;
[SerializeField] private string _scenePath;
[SerializeField] private int _buildIndex;
2019-05-04 05:54:20 -04:00
public string SceneName { get { return _sceneName; } }
public string ScenePath { get { return _scenePath; } }
public int BuildIndex { get { return _buildIndex; } }
// makes it work with the existing Unity methods (LoadLevel/LoadScene)
public static implicit operator string(SceneField sceneField) { return sceneField.SceneName; }
public int callbackOrder { get; }
void Validate()
{
2019-04-17 06:53:00 -04:00
#if UNITY_EDITOR
2019-05-04 05:54:20 -04:00
if (!EditorApplication.isPlayingOrWillChangePlaymode
2019-04-17 06:53:00 -04:00
|| EditorApplication.isCompiling
) return;
2019-05-04 05:54:20 -04:00
if (_sceneAsset == null)
{
2019-05-04 05:54:20 -04:00
_scenePath = "";
_buildIndex = -1;
_sceneName = "";
return;
}
2019-05-04 05:54:20 -04:00
_buildIndex = SceneUtility.GetBuildIndexByScenePath(_scenePath);
if (_sceneAsset != null && _buildIndex == -1)
{
2019-04-17 06:53:00 -04:00
/* Sadly its not easy to find which gameobject/component has this SceneField, at least not at this point */
2019-05-04 05:54:20 -04:00
Debug.LogError($"A scene [{_sceneName}] you used as reference has no valid build Index", _sceneAsset);
// Exit play mode - might be a bit too harsh?
#if UNITY_2019_1_OR_NEWER
EditorApplication.ExitPlaymode();
#else
EditorApplication.isPlaying = false;
#endif
}
2019-05-04 05:54:20 -04:00
#endif
}
public void OnBeforeSerialize() { Validate(); }
public void OnAfterDeserialize() { }
}
}