Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by unity_D0701EA630A7386C0FA5 · Sep 29, 2021 at 03:55 PM · editor-scriptingtoggleeditorguioninspectorgui

How to add and remove component with the same toggle in editor?

Hello, I need the possibility to add component with a click inside the editor view. In Particular i would like to add a component when the toggle is flagged and remove it when it is unflagged. I tried different solutions but each of them present the same problem, the toggle is unflagged instantly.

I don't want to use button because, i should create a button to add and one to remove the component and this for each component i want on the object....

I prefer the toggle because if it is flagged you undestand soon which component is added.

Any help is appreciated, also if you suggest a different way without toggles to do it.

My Solutions:

1st try:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEditor;
 
 [CustomEditor(typeof(Initializer))]
 public class InitializerEditor : Editor
 {
 
     bool component1 = false;
     bool component2 = false;
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
 
         Initializer script = (Initializer)target;
 
         component1= GUILayout.Toggle(component1, "Component 1");
         component2= GUILayout.Toggle(component2, "Component 2");
 
         if (component1)
         {
             if (script.gameObject.GetComponent<Component1>() == null)
             {
                 script.gameObject.AddComponent<Component1>();
             }
         }
         else
         {
             Component1 c1= script.gameObject.GetComponent<Component1>();
             if (c1 != null)
             {
                 DestroyImmediate(c1);
             }
         }
        
        if (component2)
         {
             if (script.gameObject.GetComponent<Component2>() == null)
             {
                 script.gameObject.AddComponent<Component2>();
             }
         }
         else
         {
             Component2 c2= script.gameObject.GetComponent<Component2>();
             if (c2 != null)
             {
                 DestroyImmediate(c2);
             }
         }
     }
 }

2nd try

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEditor;
 
 [CustomEditor(typeof(Initializer))]
 public class InitializerEditor : Editor
 {
 
     bool component1 = false;
     bool component2 = false;
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
 
         Initializer script = (Initializer)target;
 
         component1= GUILayout.Toggle(component1, "Component 1");
         component2= GUILayout.Toggle(component2, "Component 2");
 
         if (component1)
         {
             if (script.gameObject.GetComponent<Component1>() == null)
             {
                 script.gameObject.AddComponent<Component1>();
             }
             component1 = true;
         }
         else
         {
             Component1 c1= script.gameObject.GetComponent<Component1>();
             if (c1 != null)
             {
                 DestroyImmediate(c1);
             }
         }
        
         if (component2)
         {
             if (script.gameObject.GetComponent<Component2>() == null)
             {
                 script.gameObject.AddComponent<Component2>();
             }
             component2 = true;
         }
         else
         {
             Component2 c2= script.gameObject.GetComponent<Component2>();
             if (c2 != null)
             {
                 DestroyImmediate(c2);
             }
         }
     }
 }

3rd try

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEditor;
  
  [CustomEditor(typeof(Initializer))]
  public class InitializerEditor : Editor
  {
  
      bool component1 = false;
      bool component2 = false;
      public override void OnInspectorGUI()
      {
          DrawDefaultInspector();
  
          Initializer script = (Initializer)target;
  
          component1= GUILayout.Toggle(component1, "Component 1");
          component2= GUILayout.Toggle(component2, "Component 2");
  
          if (component1)
          {
              script.addComponent("Component1"); //i made all the checks into the initializer script
          }
          else
          {
              script.removeComponent("Component1");
          }
         
         if (component2)
          {
              script.addComponent("Component2");
          }
          else
          {
             script.removeComponent("Component2");
          }
      }
  }

If i try the following, all works perfectly and the flag remains falgged and i can unflag whenever i want.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEditor;
  
  [CustomEditor(typeof(Initializer))]
  public class InitializerEditor : Editor
  {
  
      bool component1 = false;
      bool component2 = false;
      public override void OnInspectorGUI()
      {
          DrawDefaultInspector();
  
          Initializer script = (Initializer)target;
  
          component1= GUILayout.Toggle(component1, "Component 1");
          component2= GUILayout.Toggle(component2, "Component 2");
  
          if (component1)
          {
              Debug.Log("Component1 added!");
          }
          else
          {
              Debug.Log("Component1 removed!");
          }
         
         if (component1)
          {
              Debug.Log("Component2 added!");
          }
          else
          {
              Debug.Log("Component2 removed!");
          }
      }
  }


Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Hellium · Sep 29, 2021 at 04:31 PM

SIMPLE VERSION

 [CustomEditor(typeof(Initializer))]
 public class InitializerEditor : Editor
 {
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
 
         Initializer script = (Initializer)target;
 
         DrawToggleComponent<MeshRenderer>(script.gameObject);
         DrawToggleComponent<MeshFilter>(script.gameObject);
     }
 
     private void DrawToggleComponent<T>(GameObject targetObject) where T : Component
     {
         EditorGUI.BeginChangeCheck();
         {
             bool hadComponent = targetObject.TryGetComponent(out T component);
             bool hasComponent = GUILayout.Toggle(hadComponent, typeof(T).Name);
             if(EditorGUI.EndChangeCheck())
             {
                 if (hasComponent && !hadComponent)
                 {
                     targetObject.AddComponent<T>();
                 }
                 else if(!hasComponent && hadComponent)
                 {
                     DestroyImmediate(component);
                 }
             }
         }
     }
 }


MORE COMPLEX VERSION

 [CustomEditor(typeof(Initializer))]
 public class InitializerEditor : Editor
 {
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
 
         Initializer script = (Initializer)target;

         if(DrawToggleComponent(script.gameObject, out MeshRenderer meshRenderer, onAdd: mr => Debug.Log("MeshRenderer added")))
         {
             Debug.Log("The object has a MeshFilter");
         }
         DrawToggleComponent(script.gameObject, out MeshFilter meshFilter, "My super component!");
     }

     private bool DrawToggleComponent<T>(GameObject targetObject, out T component, string label = null, Action<T> onAdd = null, Action<T> onRemove = null)
         where T : Component
     {
         bool hadComponent = targetObject.TryGetComponent(out component);
         bool hasComponent = hadComponent;
         EditorGUI.BeginChangeCheck();
         {
             hasComponent = GUILayout.Toggle(hadComponent, label ?? typeof(T).Name);
             if (EditorGUI.EndChangeCheck())
             {
                 if (hasComponent && !hadComponent)
                 {
                     component = targetObject.AddComponent<T>();
                     onAdd?.Invoke(component);
                 }
                 else if(!hasComponent && hadComponent)
                 {
                     onRemove?.Invoke(component);
                     DestroyImmediate(component);
                 }
             }
         }

         return hasComponent;
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

179 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Webview in custom Unity Editor Window? 0 Answers

GUI / Inspector Help,CustomEditor with A callback Function 0 Answers

I want to use a variable in the Unity editor source file to get it from a regular script. 0 Answers

Editor Window 1 Answer

Editor Int sliders affecting each other 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges