Why am I getting this strange behaviour?
I made my own transform component and I want it to hide the default Unity transform when added to a game object. This is the editor code I have where "Transform" = my own transform.
[CustomEditor(typeof(Transform))]
public sealed class TransformEditor : UnityEditor.Editor
{
private UnityEngine.Transform _transform;
private HideFlags _hideFlags;
void OnEnable()
{
Debug.Log("Enabled");
var dTransform = (Transform) target;
_transform = dTransform.transform;
_hideFlags = _transform.hideFlags;
_transform.hideFlags = HideFlags.HideInInspector;
Debug.Log("Flags = " + _transform.hideFlags);
}
void OnDestroy()
{
Debug.Log("Flags = " + _hideFlags);
_transform.hideFlags = _hideFlags;
}
}
For some reason what ends up happening is when I place my own transform on a game object, nothing happens, but when I remove it, the Unity transform becomes hidden.
Answer by Bunny83 · Mar 17, 2016 at 12:37 PM
First of all it's not a good idea to name your own Transform after a built in component. However if the namespaces are carefully choosen it should work but can cause a lot of namespace problems later on.
Since you change something on the transform component you should use Undo.RecordObject to make Unity aware of a change and you might have to redraw the inspector window.
Furthermore you should never "set" the hideflags to a value. The hideflags is a bitmask so you should always enable / disable certain bits by using bit operations.
Also note that OnEnable and OnDestroy are related to your Editor, not to your component.
// set the bit "HideInInspector"
_transform.hideFlags |= HideFlags.HideInInspector;
// reset the bit
_transform.hideFlags &= ~HideFlags.HideInInspector;
Of course you can store the whole bitflag and assign it back, but i don't see the point in setting and removing the hideflags each time a custom editor shows your transform or when it's closed. I guess you want to set the hideflags inside your Transform components Awake / OnEnable method and reset it in OnDestroy.
Thanks for your reply. This is my new code:
void OnEnable()
{
var dTransform = (Transform) target;
_transform = dTransform.transform;
_transform.hideFlags |= HideFlags.HideInInspector;
Debug.Log("Enable Flags = " + _transform.hideFlags);
//Undo.RecordObject(_transform, "");
Repaint();
}
void OnDestroy()
{
_transform.hideFlags &= ~HideFlags.HideInInspector;
}
But when I add my component, it's not hidden in the inspector.