Search Unity

CustomEditor: button with CanEditMultipleObjects

Discussion in 'Scripting' started by FeastSC2, Jun 5, 2020.

  1. FeastSC2

    FeastSC2

    Joined:
    Sep 30, 2016
    Posts:
    978
    I would like to make this script work with multiple objects.
    It sets the expulseAmount on multiple objects correctly, however it doesn't call the button named "Expulse!" on every object.

    What am I doing wrong?

    Code (CSharp):
    1. #if UNITY_EDITOR
    2. using UnityEditor;
    3. #endif
    4. using UnityEngine;
    5.  
    6. public class Expulsable : MonoBehaviour
    7. {
    8.     private Rigidbody body;
    9.     public Vector3 expulseAmount;
    10.  
    11.     void Awake()
    12.     {
    13.         body = GetComponent<Rigidbody>();
    14.     }
    15.  
    16.     public void Expulse(Vector3 _impulse)
    17.     {
    18.         body.AddForce(_impulse, ForceMode.Impulse);
    19.     }
    20. }
    21.  
    22. #if UNITY_EDITOR
    23. [CustomEditor(typeof(Expulsable)), CanEditMultipleObjects]
    24. public class ExpulsableEditor : Editor
    25. {
    26.     SerializedProperty expulseAmount;
    27.  
    28.     private Expulsable Expulsable;
    29.     private void OnEnable()
    30.     {
    31.         Expulsable = target as Expulsable;
    32.         expulseAmount = serializedObject.FindProperty("expulseAmount");
    33.     }
    34.  
    35.     public override void OnInspectorGUI()
    36.     {
    37.         serializedObject.Update();
    38.  
    39.         EditorGUILayout.PropertyField(expulseAmount);
    40.         if (GUILayout.Button("Expulse!")) // this only expulses one object!
    41.         {
    42.             var expulsable = (Expulsable)target;
    43.             Debug.Log($"expulsing: {expulsable.gameObject.name}");
    44.             expulsable.Expulse(expulseAmount.vector3Value);
    45.         }
    46.  
    47.         serializedObject.ApplyModifiedProperties();
    48.     }
    49. }
    50. #endif
     
  2. MatrixQ

    MatrixQ

    Joined:
    May 16, 2020
    Posts:
    87
    As far as I understand, you can't call a method on Serialized Objects like that. You could try broadcasting a message to them in order to do so.
     
  3. Xeozim

    Xeozim

    Joined:
    Oct 11, 2020
    Posts:
    2
    There is a way to do this, see this SO answer: https://stackoverflow.com/questions...le-objects-in-gui-with-caneditmultipleobjects

    For your example it would look like this:
    Code (CSharp):
    1. if (GUILayout.Button("Expulse!"))
    2. {
    3.     foreach (Object target in targets)
    4.     {
    5.         var expulsable = (Expulsable)target;
    6.         Debug.Log($"expulsing: {expulsable.gameObject.name}");
    7.         expulsable.Expulse(expulseAmount.vector3Value);
    8.     }
    9. }
     
    Aionix likes this.