首先创建一个项目,

在这个初始界面我们需要做一些准备工作,

建基础通用文件夹,

创建一个Plane 重置后 缩放100倍 加一个颜色,

任务:使用工厂方法模式 创建 飞船模型,
首先资源商店下载飞船模型,


拖拽三种类型飞船模型至unity场景中,

将三种模型完全解压缩后放进自己的Prefabs包,


在unity场景中删除三个飞船模型,

接下来编写代码:
1.创建脚本【抽象产品类】

双击AbsShip.cs编写代码:

using UnityEngine;
 public abstract class AbsShip{
     public GameObject Ship { get; set; }
     public abstract void Load();
 }
 2.创建脚本【具体产品类】

双击ShipA.cs编写代码:

using UnityEngine;
 public class ShipA : AbsShip{
     public override void Load(){
         Ship = Resources.Load<GameObject>("Prefabs/ship1");
         if (Ship != null)
             Ship = GameObject.Instantiate(Ship, new Vector3(0, 0, 0), Quaternion.identity);
     }
 }
 3.创建脚本【工厂方法类】

public abstract class AbsFactory{
     public abstract AbsShip GetShip(string type);
 }
 public class Factory : AbsFactory{
     public override AbsShip GetShip(string type){
         AbsShip ship;
         switch (type){
             case "shipA":
                 ship = new ShipA();
                 break;
             default:
                 ship = null;
                 break;
         }
         return ship;
     }
 }
4.创建脚本【主类】


using UnityEngine;
 public class Main : MonoBehaviour{
     public AbsShip ship;
     public string type;
     void Start(){
         AbsFactory shipFactory = new Factory();
         ship = shipFactory.GetShip("shipA"); 
         if (ship != null)
             ship.Load(); 
         else
             Debug.LogError("空引用");
     }
 }
 回到unity中修改预制体文件名为ship1

将Main类挂载在地面Plane上,

运行项目即可生成ship1飞船,

如果需要拓展,添加ShipB具体产品类,


using UnityEngine;
 public class ShipB : AbsShip{
     public override void Load(){
         Ship = Resources.Load<GameObject>("Prefabs/ship2");
         if (Ship != null)
             Ship = GameObject.Instantiate(Ship, new Vector3(3, 0, 0), Quaternion.identity);
     }
 }
只需修改工厂类,

public abstract class AbsFactory{
     public abstract AbsShip GetShip(string type);
 }
 public class Factory : AbsFactory{
     public override AbsShip GetShip(string type){
         AbsShip ship;
         switch (type){
             case "shipA":
                 ship = new ShipA();
                 break;
             case "shipB":
                 ship = new ShipB();
                 break;
             default:
                 ship = null;
                 break;
         }
         return ship;
     }
 }
运行项目即可完成,

End.










![【C++杂货铺】详解类和对象 [上]](https://img-blog.csdnimg.cn/direct/d88bb3783809446bb33536cfc9ce1b2c.gif)








