- Home /
Find out if gameObject is UI in 4.6
How can I easily and fast find if a certain gameObject is UI or not ?
You could check if the game object resides in the UI layer, tag it with "UI" and check against it or even assign a specific name to all your UI objects.
Answer by HarshadK · Dec 05, 2014 at 07:47 AM
Check if the GameObject contains a RectTransform component on it because UI element game objects have a RectTransform component attached to it as opposed to other objects which have a Transform component.
if(gameObject.GetComponent<RectTransform>() != null )
{
// This is a UI element since it has a RectTransform component on it
}
This will work after a fashion. But there is no reason a RectTransform can't be attached to a regular GameObject.
A better way might be to check for components from the unity engine namespace.
An even better question is why? There is no inherent difference between a UI GameObject and a regular GameObject. As per normal unity rules a GameObject is defined by the components attached to it.
@Bored$$anonymous$$ormon Nice point. I actually didn't think on the fact that user can actually add a RectTransform to regular game object making this method less usable in such instances.
Then in this case a better method I could think of is checking for CanvasRenderer since you won't add a Canvas Renderer to a game object unless you want that object to be a UI element. As there is no CanvasRenderer attached on Canvas itself one can check for Canvas component itself. I guess this will make it better than RectTransform. This method is just an extended step of previous method and still has the case of what if user applies a CanvasRenderer to a regular game object.
Or one more precise method would be to check for presence of particular UI element components from UI namespace as you have specified. But I guess it would be a little bit daunting to check for possible values under UI namespace.
Should be able to do it with reflection. It all depends on the use case. In 99% of cases the RectTransform method will work. Perfectly fine if you are building your own game. But probably a little rough for something destined for the asset store.
@Bored$$anonymous$$ormon can you post a method with how to achieve this with reflection. I would be happy to see it. I'm a bit weak with reflections. :-(