首先我们打开一个项目

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

建基础通用包

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

任务:使用【简单工厂模式】生成四种不同怪物 【按不同路径移动】
首先资源商店下载四个怪物模型


接下来我们选取四个怪物作为预制体并分别起名为Monster1-4

都完全解压缩后放进预制体包在场景中删除

准备工作做完后 接下我们做【简单工厂模式】
简单工厂不属于23设计模式中的一项但是23设计模式中抽象工厂的基础
简单工厂最低需要三个类就可以完成加上Main类中调用也就四个
首先需要 【抽象产品类】
其次需要 【具体产品类】
再其次需要【生产工厂类】
最后我们通过Main继承Mono挂载再脚本上调用即可
实现:
1.创建脚本【抽象产品类】:


using UnityEngine;
 public abstract class IMonster {
     public GameObject Monster {get;set;}
     public abstract void Load();
 }
2.【具体产品类】:

using UnityEngine;
 namespace Assets.Scripts.Product{
     class MonsterA : IMonster{
         public override void Load(){
             Monster = Resources.Load<GameObject>("Prefabs/monster1");
             if(Monster != null)
                 Monster = GameObject.Instantiate(Monster,new Vector3(0,0,0),Quaternion.identity);
         }
     }
 }
3.【生产工厂类】

using Assets.Scripts.Product;
 namespace Assets.Scripts.SimpleFactory{
     public static class Factory{
         public static IMonster GetMonster(string type) {
             IMonster monster;
             switch (type) {
                 case "monsterA":
                     monster = new MonsterA();
                     break;
                 default:
                     monster = null;
                     break;
             }
             return monster;
         }
     }
 }
 4.【控制挂载类】

using Assets.Scripts.SimpleFactory;
 using UnityEngine;
 namespace Assets.Scripts{
     public class Main : MonoBehaviour{
         public IMonster monster;
         public string type;
         private void Start(){
             monster = Factory.GetMonster("monsterA");
             monster.Load();
         }
     }
 }
我们回到unity场景中创建一个空物体改名Obj 重置位置 将Main脚本挂载

运行即可生成

接下来我们创建 多个【具体产品类】

当然也需要在其他类里添加 这就是简单工厂不好的地方 增一类 动三类


运行即可实现:

目前【简单工厂模式】已经完成
接下来我们将生成的怪物 按不同路径移动
原理:
【通过使小球(WayPoint)作为引导使怪物进行自动导航】
我们首先在unity场景中创建一个3D小球 改名为 WayPoint

将WayPoint放进预制体包 并在场景中移除

接下来通过预制体 拖拽至场景中放置不同路径

我们放大Plane

接下来创建一个空父物体代表移动路径 改名PathA
将所有WayPoint放进PathA下做子类

接下来创建移动脚本Move

将以下代码放进Move

using UnityEngine;
 public class Move : MonoBehaviour{
     public Transform[] arr;
     public float speed = 1f;       
     public int idx = 0;   
     void Start(){
         Transform path = GameObject.Find("PathA").transform;
         if (path != null){
             arr = new Transform[path.childCount];
             for (int i = 0; i < arr.Length; i++)
                 arr[i] = path.GetChild(i);
         }
         else
             Debug.LogError("查找路径点父物体失败 检查父物体名字");
     }
     private void Update(){
         Vector3 direction = arr[idx].position - transform.position;
         transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 0.1f);
         transform.Translate(Vector3.forward * speed);
         if (direction.sqrMagnitude < 1f){
             idx++;
             if (idx > arr.Length - 1)
                 idx = 0;
         }
     }
 }
将Move挂载到四个怪物预制体上
运行前
运行后




















