二段构建在unity游戏开发中运用
第一次接触到二段构建这样的设计模式是博主第一次从事手机游戏开发的时候,当时使用的游戏引擎是cocos2dx,后来就沿用到了unity游戏开发中,这里就是一个小demo介绍
效果
实现过程
public class Model : MonoBehaviour
{
public static Model Create(string resPath)
{
GameObject obj = new GameObject("Model");
//第一段构建,添加组建
Model model = obj.AddComponent<Model>();
//第二段构建,Init
if(obj && model && model.Init(resPath))
{
return model;
}
return null;
}
bool Init(string resPath)
{
GameObject obj = ResourceManager.Single.LoadOjb(resPath);
if(obj)
{
obj.transform.SetParent(transform);
obj.GetComponent<Transform>().localPosition = new Vector3(0, 0, 0);
return true;
}
return false;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
当然这个demo还涉及了一些unity基础的模型加载方式,如:Resources.Load()
public GameObject LoadOjb(string objPath)
{
GameObject Prefab = (GameObject)Resources.Load(objPath);
return Instantiate(Prefab);
}
最后附上demo的链接
https://download.csdn.net/download/lj820348789/34647580