-
Notifications
You must be signed in to change notification settings - Fork 0
Factory pattern
The factory pattern is a pattern that handle the instatiation of our objects in one single place(class). This help us by not having the instantiations spread all over our scripts, not knowing where a certain object is instantiated.
In unity/c# we can implement the factory pattern by having a factory that will instantiate a certain implementation of an abstract class that we choose, something like this:

In our example we will examine an ability system, so it will look something like this:

The ability factory will have a constructor that will search for every Ability in our assembly and then create a dictionary pointing the name(i.e fire) with the type (FireAbility.cs).
public AbilityFactory(){
var abilityTypes = Assembly.GetAssembly(typeof(Ability)).GetTypes().
Where(myType => !myType.IsAbstract && myType.IsSubclassOf(typeof(Ability)));
abilitiesByName = new Dictionary();
foreach (var type in abilityTypes)
{
var tempEffect = Activator.CreateInstance(type) as Ability;
abilitiesByName.Add(tempEffect.Name, type);
}
}Then when we want to search for a certain class to instantiate all we do is as the dictionary and if it exist, we instantiated:
public Ability GetAbility(string abilityType){
if(abilitiesByName.ContainsKey(abilityType)){
Type type = abilitiesByName[abilityType];
var ability = Activator.CreateInstance(type) as Ability;
return ability;
}
return null;
}The benefit of having all of this objects descend from an abstract class is that when we isntantiate them, we can assing a Proccess method, that will execute for each class. For example:
public class FireAbility : Ability
{
public override string Name => "Fire";
public override void Process() {
Debug.Log("Fire Creation");
}
}Home
C#
Game Design Patterns
- Command
- Flyweight pattern & Scriptable Objects
- Observer pattern
- State pattern
- Object Pool pattern
- Factory pattern
ECS
PlayFab
- Introduction
- Template Class
- Player Authentication
- Mobile Authentication
- Player Statistics
- Leaderboard
- Player Data
- Friends
Mirror