- Home /
GameObject instantiation in C# static constructor
Dear all,
i have an unusal question. How is a C# class beeing read in Unity? The question occured since there is the possibility in C# to have a static constructior (which is basically called before a class is instanciated).
My idea is to have a class file which is not attached to the scene but instanciates an gameobject on gamestart (like an overview class that administrates some gameobject-instances). I don't like the idea of having a gameobject for this on the scene and attach a script to it just for this purpose.
class Overview { // Static variable that must be initialized at run time. static List gos;
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static Overview()
{
gos = new List<GameObject>();
//gos.Add(Instanciate(Resources.load(...)));
//some other instances
}
}
Answer by frarees · Oct 09, 2014 at 03:36 PM
You can do that at editor time using things like InitializeOnLoad. Not sure if you can do that at runtime.. It needs somehow to get triggered by an instance on the scene. You could use PostProcessSceneAttribute to create an object before the scene gets built.
PostProcessSceneAttribut comes really close to the point. But I think it still has to be attached to a gameobject doesn't it?
Answer by dmg0600 · Oct 09, 2014 at 03:25 PM
You can use classes as always as long as you don't mix Unity-specific calls with threads as most of them (Instantiate, Coroutines, etc) must be called from the main thread.
What you are trying to achieve should work if you don't need to use Unity-specific methods in your Overview class.
One little thing, its Instantiate, not Instanciate.
Your answer
Follow this Question
Related Questions
Cloning Objects with Instantiate() - variables/references for added Components not stored? 3 Answers
How can I Instantiate two new GameObjects at the same time? (Attempting Asteroids style game) 2 Answers
Distribute terrain in zones 3 Answers
Inconsistencies in Instantiation Code 1 Answer
How to Instantiate a GameObject from a ScriptableObject piece of script? 0 Answers