Advertisement
gameDevTeacher

SceneDrawer

Nov 24th, 2023
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. using UnityEditor;
  2. using UnityEngine;
  3.  
  4. [CustomPropertyDrawer(typeof(SceneAttribute))]
  5. public class SceneDrawer : PropertyDrawer
  6. {
  7.  
  8.     public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  9.     {
  10.  
  11.         if (property.propertyType == SerializedPropertyType.String)
  12.         {
  13.             var sceneObject = GetSceneObject(property.stringValue);
  14.             var scene = EditorGUI.ObjectField(position, label, sceneObject, typeof(SceneAsset), true);
  15.             if (scene == null)
  16.             {
  17.                 property.stringValue = "";
  18.             }
  19.             else if (scene.name != property.stringValue)
  20.             {
  21.                 var sceneObj = GetSceneObject(scene.name);
  22.                 if (sceneObj == null)
  23.                 {
  24.                     Debug.LogWarning("The scene " + scene.name + " cannot be used. To use this scene add it to the build settings for the project");
  25.                 }
  26.                 else
  27.                 {
  28.                     property.stringValue = scene.name;
  29.                 }
  30.             }
  31.         }
  32.         else
  33.             EditorGUI.LabelField(position, label.text, "Use [Scene] with strings.");
  34.     }
  35.     protected SceneAsset GetSceneObject(string sceneObjectName)
  36.     {
  37.         if (string.IsNullOrEmpty(sceneObjectName))
  38.         {
  39.             return null;
  40.         }
  41.  
  42.         foreach (var editorScene in EditorBuildSettings.scenes)
  43.         {
  44.             if (editorScene.path.IndexOf(sceneObjectName) != -1)
  45.             {
  46.                 return AssetDatabase.LoadAssetAtPath(editorScene.path, typeof(SceneAsset)) as SceneAsset;
  47.             }
  48.         }
  49.         Debug.LogWarning("Scene [" + sceneObjectName + "] cannot be used. Add this scene to the 'Scenes in the Build' in build settings.");
  50.         return null;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement