什么是Prefab
当我们在unity中,可能会遇到这样的道具:一个需要反复使用的GameObject。虽然直接重新创建一个GameObject也可行,但当它的结构足够复杂时,我们更期望有一个能够直接复制的GameObject。这个GameObject就是Prefab。
怎么创建Prefab
首先,我们需要像正常创建GameObject一样,先在Hierarchy创建我们需要的GameObject,然后将其从Hierarchy拖到Assets窗口中,然后这个GameObject的图标就会变蓝。就说明它已经是一个合格的Prefab了。
怎么用Prefab
using UnityEngine;
public class InstantiationExample : 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.
GameObject newPrefab = Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
}
}
参考以上代码,首先需要的就是public GameObject myPrefab
,这样获取我们需要的GameObject。其次是这个Instantiate函数,使用后可以复制一个myPrefab进行实例化,然后我们可以再确定其坐标,旋转,继承关系等元素。
0 评论