Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using UnityEngine;
- using Object = UnityEngine.Object;
- using UnityEditor;
- using UnityEditor.SceneManagement;
- namespace SceneManagement
- {
- [Serializable]
- public class SceneReference : ISerializationCallbackReceiver
- {
- [SerializeField] private Object sceneAsset;
- private string scenePath = string.Empty;
- private bool IsValidSceneAsset
- {
- get
- {
- if (!sceneAsset)
- return false;
- return sceneAsset is SceneAsset;
- }
- }
- public string SceneName => sceneAsset.name;
- public string ScenePath
- {
- get => GetScenePathFromAsset();
- set
- {
- scenePath = value;
- sceneAsset = GetSceneAssetFromPath();
- }
- }
- public static implicit operator string(SceneReference sceneReference) => sceneReference.ScenePath;
- public void OnBeforeSerialize() => HandleBeforeSerialize();
- public void OnAfterDeserialize() => EditorApplication.update += HandleAfterDeserialize;
- private SceneAsset GetSceneAssetFromPath() => string.IsNullOrEmpty(scenePath) ? null : AssetDatabase.LoadAssetAtPath<SceneAsset>(scenePath);
- private string GetScenePathFromAsset() => sceneAsset == null ? string.Empty : AssetDatabase.GetAssetPath(sceneAsset);
- private void HandleBeforeSerialize()
- {
- if (IsValidSceneAsset == false && string.IsNullOrEmpty(scenePath) == false)
- {
- sceneAsset = GetSceneAssetFromPath();
- if (sceneAsset == null)
- scenePath = string.Empty;
- EditorSceneManager.MarkAllScenesDirty();
- }
- else
- {
- scenePath = GetScenePathFromAsset();
- }
- }
- private void HandleAfterDeserialize()
- {
- EditorApplication.update -= HandleAfterDeserialize;
- if (IsValidSceneAsset)
- return;
- if (string.IsNullOrEmpty(scenePath))
- return;
- sceneAsset = GetSceneAssetFromPath();
- if (!sceneAsset)
- scenePath = string.Empty;
- if (!Application.isPlaying)
- EditorSceneManager.MarkAllScenesDirty();
- }
- }
- #if UNITY_EDITOR
- [CustomPropertyDrawer(typeof(SceneReference))]
- public class SceneReferenceDrawer : PropertyDrawer
- {
- public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
- {
- return EditorGUIUtility.singleLineHeight;
- }
- public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
- {
- SerializedProperty sceneProp = property.FindPropertyRelative("sceneAsset");
- label = new GUIContent("Scene to Load");
- Rect pos = EditorGUI.PrefixLabel(position, label);
- EditorGUI.PropertyField(pos, sceneProp, GUIContent.none);
- }
- }
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement