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"));
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.
That worked, thank you :D
– MTelesExcellent! Thanks!
– DBarlok