Unity3D & prefab: instantiate prefab in script (in runtime) using public reference

Trabla: Unity3D & prefab: instantionate prefab in script (in runtime) using public reference


Solving:


1. Create prefab
2. Create new Game Object, name it "Loader"
3. Add new script to "Loader" Game Object, name script "LoaderScript"
Unity3D & prefab: instantiate prefab in script (in runtime) using public reference

4. Open script , write code

using UnityEngine;
using System.Collections
;

public class LoaderScript : MonoBehaviour {

    // this will create visible field in Unity editor
    // prefabReference will be displayed as "Prefab Reference"
    public GameObject prefabReference;

    // Use this for initialization
    void Start () {
        //===CREATING INSTANCE ====

        if (prefabReference == null) {

            Debug.LogError( "ERROR Prefab not SET !!!" );
            return;

        }


        //Creating prefab instance, placed to the root of scene
        GameObject prefabInstance = GameObject.Instantiate( prefabReference ) as GameObject;
       
        if ( prefabInstance != null) {

           
            //Add prefab as child of Game Object "Loader"
            //if remove this string brefab will be added to scene root

            prefabInstance.transform.parent = this.transform;
           
        }
   
    }

   
    // Update is called once per frame
    void Update () {
   
    }
}


Unity3D & prefab: instantiate prefab in script (in runtime) using public reference - codingtrabla tutorial 1


5. In editor drag-n-drop prefab to "Prefab Reference"
Unity3D & prefab: instantiate prefab in script (in runtime) using public reference - codingtrabla tutorial 2

6. Run scene
Result: 
Unity3D & prefab: instantiate prefab in script (in runtime) using public reference - codingtrabla tutorial 3



No comments:

Post a Comment