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"
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 () {
}
}
5. In editor drag-n-drop prefab to "Prefab Reference"
6. Run scene
Result:
No comments:
Post a Comment