Creating and Destroying GameObjects in unity

Creating GameObjects

Some Games Keeps normal object in game but some require addition gameObjects at runtime so you can simply create game objects in run time by calling Instantiate function which make copy of existing gameObject 

Example :-

public GameObject object; void Start() { for (int i = 0; i < 5; i++) { Instantiate(object); } }

It will create 5 gameObject as soon as you start game.

if object from which the copy is made doesn’t have to be present in the scene. It is more common to use a prefab dragged to a public variable from the Project panel in the editor. Also, instantiating a GameObject will copy all the Components present on the original.


using UnityEngine; public class Example : MonoBehaviour { // Reference to the Prefab. Drag a Prefab into this field in the Inspector.
public GameObject myPrefab; // This script will simply instantiate the Prefab when the game starts. void Start() { // Instantiate at position (0, 0, 0) and zero rotation. Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity); } }

in new Vector3(0,0,0) at the place of 0 you can put the coordinate of the
place where you where you want to create GameObject;

Destroying GameObjects

function of destroying gameObject is
public static void Destroy(Object obj, float t = 0.0F);

Destroy function can be use with different types like

void DestroyGameObject()
it will destroy the gameObject whatever it will reference

void DestroyScriptInstance()
        // Removes this script instance from the game object
it will actually just destroy the script component that calls it rather than destroying the GameObject the script is attached to.

void DestroyComponent()
        // Removes the rigidbody from the game object
If you just want to destroy a component from a gameObject just use above script

void DestroyObjectDelayed()
        // Kills the game object in 5 seconds after loading the object
        Destroy(gameObject, 5);
here first argument reference to gameObject and second will reference to time delay after how much time you want to destroy that gameObject


Popular posts from this blog

How to install unity editor

How to fix Android Gradle Build failed error in unity

Unity ads install error from package manager