- Home /
Keep mono reference in the asset of the private class
I started playing with custom editors and got an idea to have something like config for the editors. So I've created simple method for that purpose:
public static T LoadOrCreateConfig<T>(this Editor editor) where T : ScriptableObject
{
var path = GetRequiredConfigName<T>(editor);
var config = AssetDatabase.LoadAssetAtPath<T>(path);
if (config == null)
{
AssetDatabase.DeleteAsset(path);
config = ScriptableObject.CreateInstance<T>();
AssetDatabase.CreateAsset(config, path);
}
return config;
}
private static string GetRequiredConfigName<T>(Editor editor)
{
var mono = MonoScript.FromScriptableObject(editor);
var path = AssetDatabase.GetAssetPath(mono);
return PathUtil.ExcludeFileExtension(path) + "_config.asset";
}
So predicted common usage may look like:
public class MyCustomEditor : Editor
{
private class MyCustomEditorConfig : ScriptableObject { }
private MyCustomEditorConfig _config;
private void OnEnable()
{
_config = this.LoadOrCreateConfig<MyCustomEditorConfig>();
}
}
The problem is that, if I declare config class that way (inside editor class) then it breaks each time unity restart, it just says me that reference to the mono script is lost. I want to use private class just in order to be sure that all config is encapsulated and no one can access it (and hide it in the IntelliSense as well). I'm trying to use ScriptableObject instead of JSON, XML, INI etc., because I can create custom drawers for that config and it is easy to setup reference to the complicated objects, those like textures, gameobjects, mono etc. So the question, is there a way to keep reference to the class declared inside the other class?
Answer by Bunny83 · Nov 27, 2017 at 11:10 PM
ScriptableOBjects have the same requirement as MonoBehaviours. They need to be located in a file that has the same name as the class in order to be serialized. That means you can't make it private nor a nested class.
If you want to store config data you may just serialize them as JSON. Of course you can't store / serialize references that way but you haven't specified what the actual use would be.
The usage is to move all vital constants to the external file, so actual script user can tune behavior without digging throw code. For example this can be setup of icons for the editor, float variables which corresponds to the updating of the colliders in some custom system, etc. By the way, is that a good idea or not?
Your answer
Follow this Question
Related Questions
Scriptable Object references if not saved in AssetDatabase? 1 Answer
Why AssetDatabase.LoadAssetAtPath does not trows exception? 0 Answers
Where is Mono 1.2.5 assembly reference as used by Unity? 1 Answer
How do i convert a String into a Class reference in C# 1 Answer
How do I call a function in another gameObject's script? 5 Answers