Assets not loading correctly at startup
Hello,
I've created a series of assets, all deriving from a BaseNode abstract class that inherits from ScriptableObject. Everytime I open Unity and go in play mode, these assets don't load correctly. If I open a CustomEditor that loads those assets, it cannot find anything. But if I focus the asset in the project folder (either with left click or right click) and refresh the window, the object appears correctly and gets loaded in play mode AND every asset that is referenced by it works.
I have to do this everytime I open Unity.
Is there any reason why this happens, and how can I avoid having to click on every object? Thanks in advance!
Can you clarify what you mean when you say they "don't load correctly" in play mode? $$anonymous$$g., they are loaded and return null? They are loaded but report the wrong type (via e.g. GetType())? They are loaded but have the wrong data? Etc.
No error message actually shows, but if I, for example, use a simple command as
Resources.FindObjectsOfTypeAll(typeof(Node));
without "refreshing" those scriptableObjects, the return array is empty, whereas if I "refresh" an asset by clicking on it, the same instruction now returns an array with that node and any other node it references. This also happens in edit mode, where I open an EditorWindow which displays all these assets. While at startup no asset is visible, after I click one it shows immediately
Answer by Adam-Mechtley · Sep 15, 2017 at 11:04 AM
The problem is that you should not use Resources.FindObjectsOfTypeAll() to retrieve assets, especially at run-time, because they may not necessarily end up in your build if you do it this way. In the Editor, these assets are loaded in lazily, which is why it works after you have clicked on them once.
Instead, your component should serialize references to the nodes directly, as this will cause them to be included in the build and be loaded when your component is loaded in the scene. For example:
using System.Collections.Generic;
using UnityEngine;
class MyComponent : MonoBehaviour
{
// assign these in the Inspector
[SerializeField]
List<BaseNode> m_AllNodes = new List<BaseNode>();
}
If you need to find these objects in your project at edit time (e.g., in some custom editor window) you should instead use AssetDatabase.FindAssets():AssetDatabase.FindAssets("t:BaseNode");
Your answer
Follow this Question
Related Questions
Unity Editor Not Starting/Not Responding 1 Answer
Why is my editor taking so long to start up with internet connected? 0 Answers
because my game does not access my Scriptable Object 0 Answers
Unable to load Json to an object array 1 Answer
Resources.unload on scriptable object resets it's prefab references 0 Answers