工厂模式概念
工厂模式(Factory Pattern)是 最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
在Unity中使用工厂类
利于管理,将预制体与实例化隔开,我们不需要关心预制体是什么,需要哪些数据,工厂会替我们做好,我们只需要通过工厂的接口即可获得需要的预制体。当预制体修改时也不用在多处进行修改,只需要修改工厂即可。
代码实现
首先编写工厂的接口和抽象类
public interface IFactory<T>
{
T Create();
}
public abstract class FactorySO<T> : ScriptableObject, IFactory<T>
{
public abstract T Create();
}
现在假设我们要一个生成小球的工厂,(注意小球身上挂了名为 ball 的脚本)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "ballfactory", menuName = "Factory/BallFactory")]
public class ballFactorySO : FactorySO<ball>
{
public ball prefab;
public override ball Create()
{
ball instance = Instantiate(prefab);
return instance;
}
}
现在我们有了小球工厂,在场景中创建它!并给创建好的小球工厂拖上要生产的预制体小球,这样我们的小球工厂就完成了
现在我只要在需要生成小球的地方挂上脚本调用小球工厂即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BtnInit : MonoBehaviour
{
[SerializeField] Button btn;
[SerializeField] GameObject well;
[SerializeField] ballFactorySO Bf;
private void Awake()
{
btn.onClick.AddListener(NewSpace);
}
private void NewSpace()
{
ball n_ball = Bf.Create();
n_ball.transform.position = well.transform.position + Vector3.up;
n_ball.GetComponent<Rigidbody>().velocity = Vector3.up * 5;
n_ball.GetComponent<Rigidbody>().angularVelocity = Vector3.up * 20;
}
}