Eresor

Untitled

Oct 29th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq;
  6. using System.Reflection;
  7. using UnityEditor;
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10.  
  11. [CreateAssetMenu(menuName = "Scriptable Object Variables/Interface")]
  12. public class InterfaceVariable : ScriptableObjectInterface<IInterface>
  13. {
  14. }
  15.  
  16. public class ScriptableObjectInterface<T> : ScriptableObjectVariable<T>
  17. {
  18.     public int implementationTypeIndex;
  19.     private T _implementation;
  20.    
  21.     public override T Value
  22.     {
  23.         get
  24.         {
  25.             if (_implementation == null)
  26.             {
  27.                 _implementation = (T)Activator.CreateInstance(GetImplementations()[implementationTypeIndex]);
  28.             }
  29.             return _implementation;
  30.         }
  31.         set => _implementation = value;
  32.     }
  33.  
  34.     public Type[] GetImplementations()
  35.     {
  36.         var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes());
  37.  
  38.         var interfaceType = typeof(T);
  39.         return types.Where(p => interfaceType.IsAssignableFrom(p) && !p.IsAbstract).ToArray();
  40.     }
  41. }
  42.  
  43. [CustomEditor(typeof(InterfaceVariable))]
  44. public class ScriptableObjectInterfaceVariable : ScriptableObjectInterfaceVariable<IInterface,ScriptableObjectVariable<IInterface>>
  45. {
  46. }
  47.  
  48. public class ScriptableObjectInterfaceVariable<TBase,TVar> : Editor where TVar : ScriptableObjectVariable<TBase>
  49. {
  50.     private Type[] _implementations;
  51.  
  52.     [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
  53.     public override void OnInspectorGUI()
  54.     {
  55.         var scriptableObject = target as ScriptableObjectInterface<TBase>;
  56.  
  57.         if (scriptableObject == null)
  58.         {
  59.             return;
  60.         }
  61.        
  62.         if (_implementations == null || GUILayout.Button("Refresh implementations"))
  63.         {
  64.             _implementations = scriptableObject.GetImplementations();
  65.         }
  66.  
  67.         EditorGUILayout.LabelField($"Found {_implementations.Count()} implementations");            
  68.        
  69.         scriptableObject.implementationTypeIndex = EditorGUILayout.Popup(new GUIContent("Implementation"),
  70.             scriptableObject.implementationTypeIndex, _implementations.Select(impl => impl.FullName).ToArray());
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment