Unity Quirks and other less obvious behaviours

Listed below are a collection of links to different websites I have come across which show techniques that are nice to know because they make development easier / quicker.

 

nition.co / less obvious unity behaviours
[collapsible_item title=”Quick overview”]

  1. The .enabled property of a script (which is also the checkbox for disabling a MonoBehavior in the inspector) will only prevent Start(), Update(), FixedUpdate(), and OnGUI() from executing. e.g. OnCollisionEnter is still called even on “disabled” scripts. Contrary to the current official documentation, Awake() is also still called.
  2. If lightmapping looks all glitchy, try ticking “generate lightmap UVs” on the model to get Unity to generate its own. Also “lightmap static” needs to be set on the object.
  3. Random.Range is min inclusive, max inclusive for floats, and max exclusive for ints. So Random.Range(0, 2.0f) will return from 0 to 2.0, but Random.Range(0, 2) will only return 0 or 1.
  4. Modifying prefabs (via the Project view, or by clicking Apply in the Inspector) doesn’t actually write changes to disk until after you’ve saved. So make sure to Ctrl-S before committing changes or copying a project.
  5. Don’t Instantiate anything inside OnDestroy() or it’ll persist in the world after play stops in the editor. Unity even warns you if you try it. Of course, OnApplicationQuit() gets called before OnDestroy()
  6. Destroying a script (or its GameObject) automatically ends any Coroutines or Invokes on it. Deactivating a GameObject (SetActive(false)) kills any coroutines but has no effect on Invoke or InvokeRepeating – they just keep running. Coroutines are gone, not just paused – calling SetActive(true) won’t bring them back. Setting .enabled = false on a script has no effect on Coroutines or Invoke/InvokeRepeating.

[/collapsible_item]

 

Unity Answers question on script method execution order

[collapsible_item title=”Quick Overview”]
The order of the four methods of a script related to initialization is always:

Awake()
OnEnable()
OnLevelWasLoaded() // (only on scene changes)
Start()

—————————————–

However, if your script was disabled in the first place(via Script.enabled=false), this order changes to:

  • OnLevelWasLoaded() // is now called first, before Awake()! (only on scene changes)
  • Awake()
  • [OnEnable()/Start() are not executed until the script is actually enabled]

[/collapsible_item]

 

TheKnightsofUnity.com / Restore a crashed unsaved unity scene

[collapsible_item title=”Quick Overview”]

If you wish to recover your scene file after unity has unexpectedly stopped working.

you cannot re-launch Unity editor after the crash. If you do, you will lose the scene file and all the progress with it!

in your projects “Assets/Temp/” folder found the file name “__EditModeScene

Rename it to “Scene.unity” and presto!
Hopefully you got your scene back.

[/collapsible_item]