Skip to content

Instantly share code, notes, and snippets.

@altunsercan
Created November 28, 2020 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save altunsercan/5a4a711cb2500b4522b91f95eec9ed1e to your computer and use it in GitHub Desktop.
Save altunsercan/5a4a711cb2500b4522b91f95eec9ed1e to your computer and use it in GitHub Desktop.
Extenject: Custom Inspectors for GameObjectContexts

This base class and inspector editor combo, hides existing Extenject (zenject) properties and only displays properties under implementing class. This is helpfull when you want to create GameObjectContext without exposing the installers to the editor user.

using System;
using System.Collections.Generic;
using System.Linq;
using Zenject;
public abstract class BaseGameObjectContext : GameObjectContext
{
protected override void RunInternal()
{
this.NormalInstallers = InstallNormalInstaller();
this.NormalInstallerTypes = InstallNormalInstallerType();
this.ScriptableObjectInstallers = InstallScriptableObjects();
base.RunInternal();
}
protected virtual IEnumerable<InstallerBase> InstallNormalInstaller()
{
return Enumerable.Empty<InstallerBase>();
}
protected virtual IEnumerable<Type> InstallNormalInstallerType()
{
return Enumerable.Empty<Type>();
}
protected virtual IEnumerable<ScriptableObjectInstaller> InstallScriptableObjects()
{
return Enumerable.Empty<ScriptableObjectInstaller>();
}
}
namespace Editor
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Editor = UnityEditor.Editor;
[CustomEditor(typeof(BaseGameObjectContext),true)]
public class BaseGameObjectContextEditor : Editor
{
private List<string> members;
private void OnEnable()
{
var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
Type type = this.serializedObject.targetObject.GetType();
this.members =
type.GetFields(flags).Where(_=>_.DeclaringType==type).Select(_ => _.Name)
.Concat(
type.GetProperties(flags).Where(_=>_.DeclaringType==type).Select(_=>_.Name)
)
.ToList();
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
SerializedProperty prop = this.serializedObject.GetIterator();
if (prop.NextVisible(true)) {
do {
if (this.members.All(_ => _ != prop.name))
{
continue;
}
if (!Application.isPlaying)
{
EditorGUILayout.PropertyField(prop);
}
else
{
bool temp = GUI.enabled;
GUI.enabled = false;
EditorGUILayout.PropertyField(prop);
GUI.enabled = temp;
}
}
while (prop.NextVisible(false));
}
this.serializedObject.ApplyModifiedProperties();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment