Creating New Game Object at Run Time – Unity3D (C#)


Creating New Game Object at Run Time  – Unity3D (C#)

Games not only include driving car or make run a character but also include creating new objects. At this point, “Prefab” thing is included. In that case what is prefab? You can find thousands of definition for prefab but I will try to define it very simple.

Prefab is the core object that mostly not placed in scene. You edit its properties and clone it. For example, You want to create enemies dynamically. Create an enemy prefab, edit its texture, collider etc. and save it as a main copy. Then, you can create an instance of it in scene whenever youu want. Remember that you have a specific object, so, you need to edit it if you want some different enemy. If you have 3 different types of enemy, create 3 enemies with the desired properties and use them in scene.

Lets start. Create a cube in your scene and edit it as you want. Then create a Prefabs folder and drag it into this folder. That’s all! You created a prefab, now you can delete the cube in scene. We have an exact copy of it and we will use this copy at run time.

Instantiate gives us an exact copy of an object with a custom position. Drag this script to camera, assign your prefab cube as the public object instance and try it. A wall will be created from 9 copy of (actually clone) prefab cube.

Capture

For your games performance, you can delete the unusable clones and it does not affect the origin. You can create new clones later from prefab because it is not in scene and you can not delete it. It’s a safe way to create new objects from an original one without any risk of lose it.

©Coffee Break Codes Creating New Game Object at Run Time – Unity3D (C#)


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Creating New Game Object at Run Time – Unity3D (C#)