1

I have a class inherit MaskableGraphic. In the function Awake(), I create a gameObject. The strange thing is when stop Unity, the GameObject is not be destroyed.

public class Test : MaskableGraphic
{
    protected void Awake()
    {
        var go = new GameObject();
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
PeakCoder
  • 852
  • 8
  • 20
  • I thought they were destroyed and I'm not finding any information that they are (or are not) treated differently than Instantiated game objects. This seems like a bug. – Draco18s no longer trusts SE Apr 25 '17 at 15:03
  • Most built-in Unity UI Graphics are implemented via the MaskableGraphic subclass, I don't think this is a bug. – PeakCoder Apr 25 '17 at 15:07
  • No, I meant the fact that new game objects created via code *stick around* after the game stops running. THAT sounds like a bug. – Draco18s no longer trusts SE Apr 25 '17 at 15:09
  • 2
    Apparently all classes inheriting from UI.Graphic (and MaskableGraphic is a subclass of Graphic) have the [ExecuteInEditMode] active by default. If you notice, if you delete the object create inside Awake from the scene during runtime and you stop play mode, the object will be serialized back in the scene as soon as you go back to edit mode. It feels like it's a bug, tried on 5.5.0f3 and 5.6.0f3. – Galandil Apr 25 '17 at 15:22
  • @Galandil Thanks! – PeakCoder Apr 25 '17 at 15:25
  • 1
    Just posted a thread in the Unity forums to ask if this behaviour is intended or is indeed a bug. https://forum.unity3d.com/threads/ui-graphic-inheritance-executeineditmode.467994/ – Galandil Apr 25 '17 at 15:41
  • @Galandil Given that tag, that's probably intended (if unclear/undocumented) behavior. Props on spotting it (write an answer we can upvote?) – Draco18s no longer trusts SE Apr 25 '17 at 19:13
  • @Draco18s, done, I rewrote my comment in an answer. Thanks for the upvotes. :) – Galandil Apr 25 '17 at 19:35

1 Answers1

5

It seems that, when inheriting from UI.Graphic (and ofc from any subclass of UI.Graphic), the [ExecuteInEditMode] attribute is active by default on the class.

It can be noticed by the fact that, using your script, the go game object is created as soon Unity serializes the compiled script, and moreover, if this GO is deleted at runtime, it's serialized back by Unity when exiting play mode and going back to edit mode: typical behaviour of scripts executed in the editor and not just in play mode.

Galandil
  • 4,169
  • 1
  • 13
  • 24