I've been running into a situation where when I drag a prefab of NGUI stuff into my NGUI hierarchy in the scene, it always ends up with a UIPanel on it when it shouldn't. I dug into it and found that there must be a Unity bug that temporarily puts the new scene object at the root, which is when the OnEnable of UIImageButton is fired off, THEN gets moved to the final place in the hierarchy. NGUI always thinks there is no UIPanel rendering this new thing since it checks while the object is at the root of the project. I have reported this bug to Unity, but in the meantime I have also made these changes to UIImageButton, which seems to help as well.
Basically, in the OnEnable() function, I pass false to the UpdateImage() function, telling it not to do a MakePixelPerfect(), since that is what triggers creating the UIPanel. I don't think it's necessary to call MakePixelPerfect() during OnEnable() anyway.
void OnEnable () { UpdateImage(false); } // Gillissie added false argument.
void UpdateImage(bool makePixelPerfect = true) // Gillissie added makePixelPerfect argument.
{
if (target != null)
{
if (isEnabled)
{
target.spriteName = UICamera.IsHighlighted(gameObject) ? hoverSprite : normalSprite;
}
else
{
target.spriteName = disabledSprite;
}
if (makePixelPerfect)
{
// Gillissie - Added this condition, since calling this when dragging a prefab
// into the scene in the editor causes a UIPanel to be added unnecessarily,
// due to a bug in Unity where the OnEnable() function is called on objects
// before they reach their final place in the hierarchy, so NGUI doesn't find
// the UIPanel when first being activated.
target.MakePixelPerfect();
}
}
}