Skip to content

Instantly share code, notes, and snippets.

@chuwilliamson
Created February 8, 2018 23:40
Show Gist options
  • Select an option

  • Save chuwilliamson/c042a6c95f76d7b4040c651453f08a8d to your computer and use it in GitHub Desktop.

Select an option

Save chuwilliamson/c042a6c95f76d7b4040c651453f08a8d to your computer and use it in GitHub Desktop.

Revisions

  1. chuwilliamson created this gist Feb 8, 2018.
    37 changes: 37 additions & 0 deletions Helpers.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    using UnityEngine;
    using UnityEditor;
    using System.Collections.Generic;
    using System.Linq;
    /// <summary>
    /// Sometimes, it is useful to be able to run some editor script code in a project as soon as Unity launches without requiring action from the user.
    /// You can do this by applying the InitializeOnLoad attribute to a class which has a static constructor.
    /// A static constructor is a function with the same name as the class, declared static and without a return type or parameters.
    /// </summary>

    [InitializeOnLoad]
    public class ScriptableObjectHelpers
    {
    static List<ScriptableObject> objectsToUnload;

    static ScriptableObjectHelpers()
    {
    objectsToUnload = new List<ScriptableObject>();
    EditorApplication.playModeStateChanged += EditorApplication_playModeStateChanged;
    }

    private static void EditorApplication_playModeStateChanged(PlayModeStateChange obj)
    {
    switch (obj)
    {
    case PlayModeStateChange.EnteredPlayMode:
    objectsToUnload = Resources.LoadAll<ScriptableObject>("").ToList();
    break;

    case PlayModeStateChange.ExitingPlayMode:
    foreach (var so in objectsToUnload)
    Resources.UnloadAsset(so);
    objectsToUnload.Clear();
    break;
    }
    }
    }