Prefabs Using Scripts
Last updated
Last updated
Prefabs can be instantiated automatically or they can be instantiated using a script. In this example, we will instantiate prefabs using a script.
The script example below has a single public variable, prefab
, that is a reference to a Prefab. It creates an instance of that Prefab in the OnStart()
method.
For make this example work you need firstly create a prefab. You can do this by go in to Assets Browser, LMB -> Create -> Prefab, and enter the name of it. In our case its Red Circle.
Or you can create a simple object in Explorer configure, name it Red Square it and click on it LMB -> Create Prefab. And its also appears in Browser. If prefab with the name already exist Force rewrite the Prefab asset with new version of it.
Next, you will need to create a new object and attach the script component to it. Next, we insert our example into the script.
Then drag prefab asset from Assets Browser to our field Prefab.
Then click play, and you can see the our prefab will successfully instantiated via our script code at position (0, 0, 0). Also you can that prefab display with different icon and text in Inspector.
Because this first example is very simple, it may not seem to provide any advantage over just placing a Prefab into the Scene yourself. However, being able to instantiate Prefabs using code provides you with powerful abilities to dynamically create complex configurations of GameObjects while your game or app is running.