Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How to use the [ContextMenuItem] with a customized Editor?

Discussion in 'Scripting' started by rex20000526, May 14, 2021.

  1. rex20000526

    rex20000526

    Joined:
    Jul 29, 2019
    Posts:
    2
    I am new to the unity editor and menu stuff. Just as I am following the official tutorial, I created an editor script with some fields created by using the DrawPropertiesExcluding() function and some other fields created by manually adding EditorGUILayout. When I try to add [ContextMenuItem] before those manually added fields it just doesn't work. Anyone know the fix?

    Code (CSharp):
    1. [CustomEditor(typeof(LevelScript))]
    2. public class TesterEditor : Editor
    3. {
    4.     public override void OnInspectorGUI()
    5.     {
    6.         LevelScript myLevel = (LevelScript)target;
    7.  
    8.         DrawPropertiesExcluding(serializedObject, "position");
    9.  
    10.         serializedObject.ApplyModifiedProperties();
    11.  
    12.         EditorGUILayout.LabelField("Level", myLevel.Level.ToString());
    13.  
    14.         myLevel.position = EditorGUILayout.Vector3Field("Position", myLevel.position);
    15.  
    16.     }
    17.    
    18. }
    then I tried this:

    [ContextMenuItem("Reset Position", "ResetPosition")]
    public Vector3 position;
    but it doesn't work while if I put the ContextMenuItem above another variable it works perfectly.
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,049
    The
    EditorGUILayout.Vector3Field
    method doesn't know anything about the property or its attributes, so it can't show the context menu. You can add a custom context menu using GenericMenu but better is probably to work with SerializedProperty and EditorGUILayout.PropertyField. This lets Unity know which property the fields belongs to and should also allow it to handle the context menu attribute.
     
    rex20000526 likes this.
  3. rex20000526

    rex20000526

    Joined:
    Jul 29, 2019
    Posts:
    2
    Thanks!! I'll look into those things!