I’ve seen many threads talking about different strategies to deal with object dependencies in Unity. Because of the nature of Unity where MonoBehaviors are not instantiated with new
or even a factory methods, I was wondering how do you usually deal with object dependencies in Unity?
I’m primarily looking for responses of studios that have published many games using a specific architecture as well as having multiple people working on them. Which one do you think is usually the best? Is there any other architecture used in Unity I am not aware of?
Example:
Let’s say we have a class that holds the player data. For now let’s just say it holds the player name:
// PlayerData.cs
public class PlayerData
{
public PlayerData(string playerName)
{
PlayerName = playerName;
}
public string PlayerName { get; set; }
}
A GameManager.cs or any other class that initializes PlayerData:
// GameManager.cs
class GameManager: MonoBehavior
{
private void OnEnable()
{
var playerData = new PlayerData() { PlayerName = "Jane Doe" };
// make playerData available for MonoBehaviors that need it
}
}
Now let’s say we have a MonoBehavior
class that needs to have access to the player name.
// NameSayer.cs
class NameSayer : MonoBehavior
{
private void Start()
{
// Get player name from PlayerData and print it
// Singleton, Dependency Injection, Service Locator, Scriptable Object, something else?
}
}
As long as you provide what the MonoBehavior needs, they will do what they are supposed to do. What’s the best way to make what MonoBehaviors need explicit in code? Which architecture is the best to minimize problems where people use a MonoBehavior and they get a run time error later because they didn’t know it required a Singleton to be initialized with some values to work properly?