Unity3D - 设计模式 - 工厂模式
工厂模式:以食物生产为例
1. 一个生产食物的工厂(此项 需要建立两个类:食物基类<Food>,工厂类<Factory>)
2. 可以生产不同的食物(此项 建立食物的具体子类,均继承食物的基类)
3. 运行程序生成不同的食物(此项 建立程序运行的主类 继承鱼MonoBehaviour,创建工厂类变量、食物基类变量,然后再Start方法里给食物基类变量赋值<通过传入参数的不同 将父类指向一个子类>)
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 测试工厂模式 /// </summary> // 创建实物的基类 public class Food { public virtual void ShowMe () { Debug.Log ("这是实物基类"); } } // 西红柿类 public class TomatoFood:Food { public override void ShowMe () { // 掉父类方法 base.ShowMe (); Debug.Log ("TomatoFood"); } } // 鸡蛋 public class EggFood:Food { public override void ShowMe () { base.ShowMe (); Debug.Log ("EggFood"); } } public class Factory { public Food MakeFood (string name) { if (name == "egg") { return new EggFood (); } else if (name == "tomato") { return new TomatoFood (); } return null; } } public class Main : MonoBehaviour { Factory factory = new Factory (); Food food1; Food food2; public void Start () { food1 = factory.MakeFood ("egg"); food1.ShowMe (); food2 = factory.MakeFood ("tomato"); food2.ShowMe (); } }
以Resources加载游戏物体为例
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SpriteFactory : MonoBehaviour { public Object[] allSprit; private int allIndex = 0; private Transform canvasTransform; /// <summary> /// 加载 Resources 文件夹下的资源 /// </summary> void Start () { canvasTransform = GameObject.Find ("Canvas").transform; LoadSprite ("Number"); } void Update () { if (Input.GetKeyDown (KeyCode.A)) { allIndex++; GameObject tempObj = GetImage (allIndex); tempObj.transform.parent = canvasTransform; tempObj.transform.position = new Vector3 (allIndex * 50, 0, 0); } } /// <summary> /// 加载Resources文件夹下指定名称的资源 /// </summary> /// <param name="name">指定名称</param> public void LoadSprite (string name) { allSprit = Resources.LoadAll (name); } /// <summary> /// 加载指定索引的资源,并把该资源显示出来 /// </summary> /// <returns>返回一个新生成的物体,该物体显式刚刚加载的资源</returns> /// <param name="index">给出要加载资源的一个索引</param> public GameObject GetImage (int index) { GameObject tempObj = new GameObject ("tempObj"); Image tempImage = tempObj.AddComponent<Image> (); tempImage.sprite = allSprit [index] as Sprite; return tempObj; } }