Search Unity

Prefabs in Resources folder and reference cache approach

Discussion in 'Editor & General Support' started by YoungDeveloper, Jul 7, 2015.

  1. YoungDeveloper

    YoungDeveloper

    Joined:
    Jun 28, 2013
    Posts:
    65
    I was working on a resource database creation, and i needed to store a reference to the manager itself. Database itself contain fields which are created from the inspector.

    One approach was to create a gameobject as a manager, keep the component there and store the singleton or static reference on awake. This is not a bad approach, but this means you have to actually have a forever living gameobject with dontdestroyonload.

    Second approach seems a lot nicer, but im not sure if it wont produce any possible errors.
    I made a static initalizer on a prefab which is located in resources folder (not on any scene).

    public class MyScriptName : MonoBehaviour {

    private static MyScriptName _instance;
    static MyScriptName() {
    Debug.LogWarning("STATIC INITIALIZER");
    GameObject resource = (GameObject)Resources.Load("path", typeof(GameObject));
    _instance = resource.GetComponent<MyScriptName>();
    }
    }

    So this located only in resources folder only, when i press play the debug is executed!
    I'd like to know why, because its not in any scene. Looks like all monos are called regardless of the location.

    Kind of second question

    I'd also want to know one thing, what exactly is happening here?
    Everything stored in resources is included in the build, on the drive, but nothing is stored in memory.
    So how can i get a reference on non existing class?
    Is the gameobject created from the resource load fucntion and i store the reference there, is there any chance i might loose the reference because it's not in any scene.

    Thanks
     
    Last edited: Jul 7, 2015