- Home /
Custom Editor for interfaces
Hi guys I've problem with custom editor for enemies.
In IEnemy interface I have two methods: "Attack" and "Die".
So I made IEnemyEditor script and on the top I wrote this:[CustomEditor(typeof(IEnemy), true)].
In IEnemyEditor i'd like to have two buttons called "Attack Player" and "Die", which execute before mentioned methods Attack.
I've few enemies which inherits from IEnemy interface and when i click on object with that enemy script it should show these two buttons, but it don't.
Do you have any ideas how to fix that ?
.
IEnemy:
public interface IEnemy
{
void Attack();
void Die();
}
.
IEnemyEditor:
[CustomEditor(typeof(IEnemy), true)]
public class IEnemyEditor : Editor
{
private IEnemy enemy;
public override void OnInspectorGUI()
{
if (!Application.isPlaying)
return;
if (enemy == null)
enemy = (IEnemy) target;
DrawInGameOptions();
}
private void DrawInGameOptions()
{
EditorGUILayout.LabelField("In Game Options", EditorStyles.centeredGreyMiniLabel);
if (GUILayout.Button("Attack Player"))
enemy.Attack();
if (GUILayout.Button("Die"))
enemy.Die();
}
}
.
Enemy (Spider):
public class Spider : MonoBehaviour, IEnemy
{
public void Attack()
{
}
public void Die()
{
}
}
Answer by CLX_Software · Jul 20, 2018 at 08:34 PM
You should not be able to build a custom inspector for classes that do not inherit from MonoBehaviour. Your interfaces and your spider class do not inherit from MonoBehaviour, and there for are not considered a 'Component'. That means they should never show in the inspector. That is why you cannot customize it.
https://docs.unity3d.com/Manual/editor-CustomEditors.html
Text From Link:
When you create a script in Unity, by default it inherits from MonoBehaviour, and therefore is a Component which can be placed on a game object. When placed on a game object, the Inspector displays a default interface for viewing and editing all public variables that can be shown - such as integers, floats, strings, Vector3’s, etc .
I made a mistake writing this post. Now there is $$anonymous$$onoBehaviour in script, but problem is still not solved ;/
Answer by HoleMaker · Nov 24, 2020 at 11:45 AM
I've encountered a simillar issue, but I don't think it has a nice, clean solution. The way I usually solve this issue is to create a common, abstract base class for some classes of same type (in your code sample it would be something like "NPC class" or "BaseEnemy class") and then check for interface in a common editor class.
Drawback is that this might violate composition over inheritance principle.
Your answer
Follow this Question
Related Questions
Working with Unity Editor 1 Answer
Prefabs aren't saving with Undo.RecordObject 4 Answers
Multiple Cars not working 1 Answer
List of CustomEditor inside CustomEditor 1 Answer
Microsoft Visual C# Compiler error 0 Answers