Trabla: Unity3D & prefab: loading & instantiating prefab from Resources in script (in runtime)
Solving:
Overview:
1. Create "Resources"(!!!name is mandatory) folder in Assets
2. Create folder "Prefabs"(any name you like) for prefabs in "Resources" folder
3. Create prefab and put it into "Prefabs" folder
4. Create Game Object in scene , add script component, create script for loading & instantiating prefab from Resources
1. Create "Resources"(!!!name is mandatory) folder in Assets
2. Create folder "Prefabs"(any name you like) for prefabs in "Resources" folder
3. Create prefab and put it into "Prefabs" folder:
3.1 Create GameObject
3.2 Rename it to "TestPrefab" and add any component you want
3.3 Drag-n-drop "TestPrefab" into "Prefabs" folder
3.4 Delete "TestPrefab" from "Hierarchy"
4. Create Game Object in scene , add script component, create script for loading & instantiating prefab from Resources:
4.1 Create GameObject
4.2 Rename it to "Loader"
4.3 Add Component "New Script" and name it "LoaderScript"
4.4 Open script in editor
4.5 Write code:
using UnityEngine;
using System.Collections;
public class LoaderScript : MonoBehaviour {
// Use this for initialization
void Start () {
//====== LOADING FROM RESOURCES =====
//Game Object to store prefab metadata from resources
GameObject prefab = null;
//Path in Resourses folder
string pathToPrefab = "Prefabs/TestPrefab";
//Loading from "Resources/Prefabs/TestPrefab"
prefab = Resources.Load<GameObject>( pathToPrefab );
if( prefab == null ){
Debug.LogError( "ERROR LOADING PREFAD from Resources/Prefabs/TestPrefab" );
return;
}
// Now runtime knows about "TestPrefab" and can create instance
//===== CREATING INSTANCE =========
GameObject prefabInstance = GameObject.Instantiate( prefab ) 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 () {
}
}
4.6 Run scene
Result
No comments:
Post a Comment