Hi all,
It it possible to pass a prefab as a parameter into a function?
For example
Spawn (Rocket_prefab);
and the the spawn function does an Instantiate of type “Rocket_prefab”
???
Thanks
Hi all,
It it possible to pass a prefab as a parameter into a function?
For example
Spawn (Rocket_prefab);
and the the spawn function does an Instantiate of type “Rocket_prefab”
???
Thanks
No problem. You must have a variable somewhere in the caller script to define the prefab, then you can pass this variable to the instantiating routine (actually, any object of the same type declared in the routine may be passed and cloned). For instance:
var prefab1: GameObject; // set these variables at the Inspector, or read from the
var prefab2: GameObject; // Resources folder with Resources.Load
// In the calling code:
...
var obj1 = Spawn(prefab1);
obj1.transform.position = point1;
var obj2 = Spawn(prefab2);
obj2.transform.position = point1 + offset;
...
// the Spawn routine:
function Spawn(prefab: GameObject): GameObject {
return Instantiate(prefab, Vector3.zero, Quaternion.identity);
}
The Spawn routine could be declared with other parameter types, like Transform, Rigidbody, GUIText - but the type returned would be the same as the parameter.
You can use Resources.Load instead of setting it in the Inspector. The reasons why you wouldn't want to do that are, everything in a /Resources folder needs to be loaded before any level can run, and these resources are always loaded. Unity goes out of its way to not have any resources loaded that aren't currently needed, which is generally a really great thing.
– anon98805514