How to Create and Use Prefabs in Unity
Notes:
How to Create Prefabs in Unity:
How to use Prefabs in Unity:
Assets: Prefabs
Prefab: reusable template
Prefab is a wrapper for a game object.
Once you create a prefab you can create infinite number of instances of it.
Any edits made to a prefab are immediately affected to all of its instances.
Note: Prefabs are created to reuse game objects in many scenes.
Crate_Mover.cs code:
using UnityEngine;
public class Crate_Mover : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.LeftArrow)) {
this.transform.position = this.transform.position + new Vector3 (-3f, 0f, 0f) * Time.deltaTime;
}
if (Input.GetKey (KeyCode.RightArrow)) {
this.transform.position = this.transform.position + new Vector3 (3f, 0f, 0f) * Time.deltaTime;
}
if (Input.GetKey (KeyCode.UpArrow)) {
this.transform.position = this.transform.position + new Vector3 (0f, 3f, 0f) * Time.deltaTime;
}
if (Input.GetKey (KeyCode.DownArrow)) {
this.transform.position = this.transform.position + new Vector3 (0f, -3f, 0f) * Time.deltaTime;
}
}
}
Steps:
Create a prefab:
Assets menu - Create - Prefab - Name the prefab - Enter - Drag the object to the prefab
Creating instance:
Drag the prefab into Hierarchy panel to create an instance
Play:
Save the scene:
File menu - Save Scenes - Name the scene - Save
Using prefab in another scene:
Create a scene:
File menu - New scene
Creating instance:
Drag the prefab into Hierarchy panel to create an instance
Play: