- Home /
Instantiate Prefab and Initialize it's variables
Hello, everyone. I have a prefab object called "Unit" that is a simple cube with a script attached. This script has a few variables that have to be set when I instatiate the prefab. The variables are a MonoBehaviour Script (called myReceiver) and an Int called (myIndex). How can I set them the moment I instantiate the object?
GameObject go = (GameObject)Instantiate(Resources.Load("Unit"));
PS. I'm using C#.
Thanks
Answer by rutter · Apr 10, 2012 at 08:51 PM
You have a reference to go
, the GameObject that you just created. From there, you can use `GetComponent()` to find its components and/or behavior scripts; the particular configuration steps after that will depend on what exactly you're trying to do.
Supposing you have a MonoBehaviour, Foo
, which has a public function like so:
public void DoStuff(int x) { ... }
You could then call that function like so:
go.GetComponent<Foo>().DoStuff(5);
If you're not sure whether a particular component is attached to some object, you can check if calling GetComponent()
for that class returns null. You can also use AddComponent()
to add a specific component.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070139im_/https://answers.unity.com/themes/thub/images/avi.jpg)