I wanted to share the main design pattern I decided to adapt for all my scripts.
Essentially, every script I create inherits from a “GameScript” class.
This GameScript does three things:
- It caches the Transform
- Provides easy manner to get and set transform properties (position, rotation)
- Acts as a service locator for any classes which inherit it.
//All managers are serialized here in Main class.
public class Main
{
public static Main mainInstance;
[SerializeField] private InventoryManager inventoryManager;
[SerializeField] private PlayerController playerController;
public InventoryManager GetInventoryManager()
{
return inventoryManager;
}
}
//Base class for all scripts
public abstract class GameScript : MonoBehaviour
{
//Cache the Transform
protected Transform m_transform = null;
protected Transform _Transform
{
get{
return m_transform;
}
}
protected Main m_mainClass; //The main manager. Responsible for keeping the reference of all managers
protected void Init()
{
m_transform = gameObject.transform; //Cache the transform
m_mainClass = Main.mainInstance; //The ONLY singleton existing .
}
//Provides manner to get and set transform properties (position, rotation)
protected Vector3 _Position
{
get{
return _Transform.position;
}
set{
_Transform.position = value;
}
}
//Service Locators
protected InventoryManager _Inventory {
get {
return mainClass.GetInventoryManager();
}
}
}
public class PlayerController: GameScript
{
void Awake()
{
base.Init();
}
//Here the "magic" happens
void Update()
{
_Transform.LookAt(...) //Accessing the cached transform
_Position = ... //Set the position, rotation, scale via cached transform
_Inventory.AddItem(); //Inventory is located in base class.
}
}
The purpose of using the base class as a service locator here is so that any scripts created do not have to be concerned with how to get the reference to the managers classes such as Inventory. It is the base class responsibility to handle this. The references could be singletons, they could not be. It doesn’t matter to any scripts which inherit GameScript.
What are people’s thoughts on this? Anyone else uses something similar to this?
