I am new to Unity but have some experience of coding in C++ and C#. I am currently trying to get my head around the best way of structuring code with Unity, and understand the way that scenes, assets and components work.
However, I am a little stumped with how executable code can sit outside of a particular scene, and if it does how it is instantiated and referenced from other code. The type of thing that would typically fall under this category would be 'Manager' type classes that need to be accessible in a lot of places in code. I understand that the need for these is significantly reduced with Unity - this is one of the reasons I have decided to use it, but I still have a need for this type of thing.
I would be extremely grateful for any pointers as to how this should be done.
I'm always have a special scene with my manager scripts in it. That scene is loaded first and gets never loaded again. Within your script you should cal DontDestroyOnLoad() on your gameobject. That will prevent that gameobject (and all childs and scripts that are attached) from being destroyed at LoadLevel.
You may also consider a "unity style singleton". There are many ways to implement a singleton. unsave, save and very save, but it depends on what you need.
I'll guess you use C#
// unsave
public class MyGame : MonoBehaviour
{
public static MyGame instance = null;
void Awake()
{
instance = this;
}
}
Or the better one:
// save
public class MyGame : MonoBehaviour
{
private static MyGame m_Instance = null;
public static MyGame instance
{
get
{
if (m_Instance == null)
m_Instance = (MyGame)FindObjectOfType(typeof(MyGame));
return m_Instance;
}
}
}
Here the "super save" version, but it don't make much sense because most of time you need to setup some references to prefabs and stuff in the editor. If you create that GO from scratch it would be "naked".
// super save
public class MyGame : MonoBehaviour
{
private static MyGame m_Instance = null;
public static MyGame instance
{
get
{
if (m_Instance == null)
{
m_Instance = (MyGame)FindObjectOfType(typeof(MyGame));
if (m_Instance == null)
{
GameObject GO = new GameObject("MyGame");
m_Instance = GO.AddComponent<MyGame>();
}
}
return m_Instance;
}
}
}
All scripts outside of folders named "Editor" are included in builds, even if they aren't used, as far as I know. (Most other assets can be included in the project but not be included in the build if they aren't necessary for the scene.) Regardless, even if I misinterpreted that fact at some point, there's no problem with what you want to do. At the very least, the scripts you need will be included. At least they always have been for me. ;-)