Created
January 21, 2019 09:44
-
-
Save volblob/200d3f97c93bbafcca53a51487d94492 to your computer and use it in GitHub Desktop.
Code to illustrate new reloading of ScriptableObject in Unity 2019.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using UnityEngine; | |
using UnityEditor; | |
// Save this to a file named ScriptableObjectReload.cs and run this example with menu item "Examples" -> "Reload ScriptableObject Example" | |
public class ScriptableObjectReload : ScriptableObject | |
{ | |
const string assetPath = "Assets/ScriptObject.asset"; | |
public string stringValue; | |
[MenuItem("Examples/Reload ScriptableObject Example")] | |
public static void ReloadScriptableObject() | |
{ | |
AssetDatabase.DeleteAsset(assetPath); | |
const string initialValue = "Hello"; | |
Debug.Log("Creating ScripableObject"); | |
{ | |
// Create asset with ScriptableObject | |
var scriptObj = ScriptableObject.CreateInstance<ScriptableObjectReload>(); | |
scriptObj.name = "ScriptObject"; | |
scriptObj.stringValue = initialValue; | |
AssetDatabase.CreateAsset(scriptObj, assetPath); | |
AssetDatabase.SaveAssets(); | |
} | |
// Load the asset with the ScriptableObject | |
var loadedObject = AssetDatabase.LoadAssetAtPath<ScriptableObjectReload>(assetPath); | |
if (loadedObject != null && loadedObject.stringValue == initialValue) | |
{ | |
Debug.Log("Successfully loaded newly created ScripableObject"); | |
} | |
else | |
{ | |
Debug.LogError("Failed to load newly created ScripableObject"); | |
} | |
Debug.Log("Wait before modifying ScriptableObject to ensure modified asset file timestamp is more than 1 sec different"); | |
System.Threading.Thread.Sleep(1100); | |
Debug.Log("Modifying ScriptableObject as text file"); | |
const string modifiedValue = "HelloWorld!"; | |
{ | |
// modify the asset file on disk | |
string text = File.ReadAllText(assetPath); | |
text = text.Replace(initialValue, modifiedValue); | |
File.WriteAllText(assetPath, text); | |
} | |
if (loadedObject.stringValue == initialValue) | |
{ | |
Debug.Log("ScriptableObject not yet reloaded"); | |
} | |
else | |
{ | |
Debug.LogError("ScriptableObject should not be reloaded"); | |
} | |
Debug.Log("Refresh assets"); | |
AssetDatabase.Refresh(); | |
if (loadedObject != null && loadedObject.stringValue == modifiedValue) | |
{ | |
Debug.Log("Successfully reloaded ScripableObject"); | |
} | |
else | |
{ | |
Debug.LogError("Failed to reload ScripableObject"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment