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.
I found a walkaroud to directly execute the context menu. It’s not perfect but at least work.
private delegate bool DelegateExecuteMenuItemWithTemporaryContext(string menuItemPath, UnityEngine.Object[] objects);
private static DelegateExecuteMenuItemWithTemporaryContext ExecuteMenuItemWithTemporaryContext;
public static void RemoveRectTransform(this GameObject gameObject)
{
var rectTransform = gameObject.GetComponent<RectTransform>();
if (rectTransform != null)
{
if (ExecuteMenuItemWithTemporaryContext == null)
{
ExecuteMenuItemWithTemporaryContext = typeof(EditorApplication).GetMethod("ExecuteMenuItemWithTemporaryContext", BindingFlags.Static | BindingFlags.NonPublic)
.CreateDelegate(typeof(DelegateExecuteMenuItemWithTemporaryContext)) as DelegateExecuteMenuItemWithTemporaryContext;
}
ExecuteMenuItemWithTemporaryContext("CONTEXT/Component/Remove Component", new UnityEngine.Object[] { rectTransform });
}
}
2 Likes