Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question How can I remove a RectTransform to revert to a normal Transform by editor script?

Discussion in 'Editor & General Support' started by jayatubi, Jun 3, 2020.

  1. jayatubi

    jayatubi

    Joined:
    Dec 9, 2013
    Posts:
    143
    Hi,

    In the editor script I could add a RectTransform to a game object by
    gameObject.AddComponent<RectTransform>()
    .

    Then I'd like to find a way to do the oppersite operation to revert to normal Transform.

    I tried
    Destroy(gameObject.GetComponent<RectTransform>()
    but failed with an error:
    Can't destroy RectTransform component of. If you want to destroy the game object, please call 'Destroy' on the game object instead. Destroying the RectTransform component is not allowed.

    There is nothing else on this game object depend on that RectTransform and it could be removed by the context menu. I want to do the same thing as the context menu in an editor script.
     
  2. jayatubi

    jayatubi

    Joined:
    Dec 9, 2013
    Posts:
    143
    I found a walkaroud to directly execute the context menu. It's not perfect but at least work.
    Code (CSharp):
    1. private delegate bool DelegateExecuteMenuItemWithTemporaryContext(string menuItemPath, UnityEngine.Object[] objects);
    2. private static DelegateExecuteMenuItemWithTemporaryContext ExecuteMenuItemWithTemporaryContext;
    3.  
    4. public static void RemoveRectTransform(this GameObject gameObject)
    5. {
    6.     var rectTransform = gameObject.GetComponent<RectTransform>();
    7.     if (rectTransform != null)
    8.     {
    9.         if (ExecuteMenuItemWithTemporaryContext == null)
    10.         {
    11.             ExecuteMenuItemWithTemporaryContext = typeof(EditorApplication).GetMethod("ExecuteMenuItemWithTemporaryContext", BindingFlags.Static | BindingFlags.NonPublic)
    12.                 .CreateDelegate(typeof(DelegateExecuteMenuItemWithTemporaryContext)) as DelegateExecuteMenuItemWithTemporaryContext;
    13.         }
    14.         ExecuteMenuItemWithTemporaryContext("CONTEXT/Component/Remove Component", new UnityEngine.Object[] { rectTransform });
    15.     }
    16. }
     
    cbFaiz and hogwash like this.