- Home /
Link variables of a script in dynamically instantiated prefab before start is called
It's actually 2 questions. What's the best way to set links of a script of an instantiated prefab, and is there any way to do that before the instantiated prefab's script calls it's start function?
I wat to set a bool. my start function looks something like this
void Start ()
{
if(boolValue)
{
//do stuff
}
else
{
//do other stuff
}
}
Answer by amphoterik · Jul 26, 2013 at 12:22 PM
Use the Awake() function. It is just like start, accept it runs before start:
void Awake()
{
//do what you need to do here.
}
If you need to be able to pass a variable in to the method in question I would instead not use either the Start or Awake methods. Instead I would create a new method and put all my startup stuff in there. Then just have whatever script instantiates the object call that method. It would look like:
//object script. Assume is it named "MyScript"
public void Init(bool value)
{
//complete all if your startup stuff here based on the parameters
}
Then in the script that creates the object:
GameObject myObj = (GameObject)Instantiate(...);
myObj.GetComponent<MyScript>().Init(true); // or false
I am 99.9% sure the setup will get called before the object's update. I believe the created object will queue and begin firing off in the next round of updates.
I taught about that, but i can't give it a parameter. Or is there any way to give it a parameter?
Oh, I see now what you are trying to do. I would ins$$anonymous$$d not use either the Start or Awake methods. Ins$$anonymous$$d I would create a new method and put all my startup stuff in there. Then just have whatever script instantiates the object call that method. How does that sound?
that sounds good. So i should move all the stuff from my start function in an Setup function, then add a new function like SetParameters and then when i instantiate i should do something like: Instantiate(); SetParameters(); Setup();
do i know for sure that Update() won't be called before if i want to use stuff i initialize in SetParameters inside Update()? Just realized it doesn't matter if update is called before becouse i can check if the variables are initialized or not.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110917im_/https://answers.unity.com/themes/thub/images/avi.jpg)