- Home /
How to wait for Start() to run when calling InstantiateObject()
I'm having a problem with timing. When I instantiate an object I add it to the map using the object's Start() method. So, in some parts of my code, I need the start method to be ran before I can continue with the method. Or else I get in the situation I'm in now where multiple trees are being put on the same tile because they don't know it's already occupied.
I know I could use a coroutine to wait for an amount of time to pass, but it would be better if I didn't have to guess at how long the instantiation will take.
Answer by iwaldrop · Aug 02, 2014 at 09:25 PM
Unity's lazy loading of objects via the Start method is fine in most cases. If you can't simply move that logic to Awake, then it sounds like need tighter control over your object creation cycle. Here's what I do:
Use Prefabs. They allow you to setup defaults on objects which can then be modified in the object creation process.
Use Constructor-like methods to build your objects. Here, you will pass in the data that you need and know that the object is setup by the time the method completes. This looks something like this:
public SomeObject CreateObject(ObjectManifest manifest) { SomeObject result = null; if (manifest != null) { GameObject go = GameObject.Instantiate(prefab) as GameObject; result = go.GetComponent(); result.SetInfo(manifest); } return result; }
public class SomeObject : MonoBehaviour { public SetInfo(ObjectManifest manifest) { // apply all settings from the manifest to the object, ex: result.enabled = manifest.startEnabled;
// or pass nothing and do your Start() stuff here } }
Again, doing it this way will ensure that your object is fully initialized by the time you get the reference back. Note that I use the term 'manifest' loosely, and that it is an abstraction for the notion of passing in some configuration data, be it in the form of a custom class or a bunch of method arguments.
Thanks! I didn't even know there was an Awake method, oops. I put my logic in there and it works perfectly. I appreciate the response.
Your answer
Follow this Question
Related Questions
instantiating at a random time 1 Answer
continuous shooting 1 Answer
Help Guitar Hero Style or similar 0 Answers
Respawn Player Using a Coroutine 0 Answers