Simple tu use and foolproof. It uses abstraction to make it almost invisible on your code and easy to reuse it.
- Inherid
PrefabProduct
on your product controller class:
public class ProductA : PrefabProduct
{
public override void Initialize()
{
Debug.Log($"Unique initialization for <b>{this.GetType()}<b>");
}
// Add prefab control functions here
}
- Create a prefab for the product and attach your product controller:
- Inherid
PrefabFactory
with the desired type of product on your factory controller class:
public class FactoryA : PrefabFactory<ProductA>
{
public override PrefabProduct CreateProduct(Vector3 position = new Vector3(), Quaternion rotation = new Quaternion())
{
PrefabProduct newProduct = base.CreateProduct(position, rotation);
Debug.Log($"Unique behavior for <b>{this.GetType()}</b> while creating <b>{newProduct.GetType()}</b>");
return newProduct;
}
}
- Create a GameObject, attach your factory controller and assign your prefab with the product controller to the variable
Product Prefab
:
-
Repeat previous steps for each product
-
Create a manager to control all your factories:
public class FactoryManager : MonoBehaviour
{
[SerializeField] FactoryA _FactoryA;
[SerializeField] FactoryB _FactoryB;
// More factories...
private void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
ProductA productA = (ProductA)_FactoryA.CreateProduct();
}
if (Input.GetKeyDown(KeyCode.W))
{
PrefabProduct productB = _FactoryB.CreateProduct(Vector3.up, Quaternion.identity);
}
}
}
- Create a GameObject, attach your factory manager and assign your factory controllers:
- Any Unity version
- Any pipeline (Build-in, URP, HDRP, etc)
⭐ Star if you like it
❤️️ Follow me for more