Convert Figma logo to code with AI

Habrador logoUnity-Programming-Patterns

Implementations of programming design patterns in Unity with examples in C# when to use them.

1,891
257
1,891
2

Top Related Projects

Unity C# reference source code.

:tea: All Gang of Four Design Patterns written in Unity C# with many examples. And some Game Programming Patterns written in Unity C#. | 各种设计模式的Unity3D C#版本实现

Unity Open Project #1: Chop Chop

Quick Overview

Unity-Programming-Patterns is a GitHub repository that demonstrates various programming patterns and design principles in Unity game development. It provides practical examples and implementations of common patterns such as Singleton, Object Pool, and State Machine, helping developers improve their code structure and efficiency in Unity projects.

Pros

  • Offers a wide range of programming patterns specifically tailored for Unity development
  • Includes clear, well-commented code examples for each pattern
  • Provides practical implementations that can be easily adapted to real-world projects
  • Serves as an educational resource for both beginners and experienced Unity developers

Cons

  • Some patterns may not be optimized for all use cases or project scales
  • Limited documentation outside of code comments
  • May not cover all possible variations or advanced implementations of each pattern
  • Repository updates may be infrequent

Code Examples

  1. Singleton Pattern:
public class Singleton<T> : MonoBehaviour where T : Component
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();
                if (_instance == null)
                {
                    GameObject obj = new GameObject();
                    obj.name = typeof(T).Name;
                    _instance = obj.AddComponent<T>();
                }
            }
            return _instance;
        }
    }

    protected virtual void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else if (_instance != this)
        {
            Destroy(gameObject);
        }
    }
}

This code implements a generic Singleton pattern in Unity, ensuring only one instance of a component exists.

  1. Object Pool Pattern:
public class ObjectPool : MonoBehaviour
{
    public GameObject prefab;
    public int poolSize = 10;

    private List<GameObject> pool;

    void Start()
    {
        pool = new List<GameObject>();
        for (int i = 0; i < poolSize; i++)
        {
            GameObject obj = Instantiate(prefab);
            obj.SetActive(false);
            pool.Add(obj);
        }
    }

    public GameObject GetObject()
    {
        foreach (GameObject obj in pool)
        {
            if (!obj.activeInHierarchy)
            {
                obj.SetActive(true);
                return obj;
            }
        }
        return null;
    }

    public void ReturnObject(GameObject obj)
    {
        obj.SetActive(false);
    }
}

This code demonstrates a simple Object Pool implementation, which can improve performance by reusing game objects instead of instantiating and destroying them repeatedly.

  1. State Machine Pattern:
public abstract class State
{
    protected StateMachine stateMachine;

    public virtual void Enter() { }
    public virtual void Exit() { }
    public virtual void Update() { }

    public void SetStateMachine(StateMachine stateMachine)
    {
        this.stateMachine = stateMachine;
    }
}

public class StateMachine : MonoBehaviour
{
    private State currentState;

    public void SetState(State newState)
    {
        if (currentState != null)
            currentState.Exit();

        currentState = newState;
        currentState.SetStateMachine(this);
        currentState.Enter();
    }

    void Update()
    {
        if (currentState != null)
            currentState.Update();
    }
}

This code showcases a basic State Machine pattern implementation, useful for managing complex game logic and character behaviors.

Getting Started

To use these patterns in your Unity project:

  1. Clone the repository or download the desired pattern scripts.
  2. Import the scripts into your Unity project's Assets folder.
  3. Attach the relevant scripts to GameObjects or create new scripts that inherit from the pattern classes.
  4. Customize the implementations to fit your specific game requirements.

For example, to use the Singleton pattern:

public class GameManager : Singleton<GameManager>
{
    //

Competitor Comparisons

Unity C# reference source code.

Pros of UnityCsReference

  • Official Unity source code, providing direct insight into Unity's internal workings
  • Comprehensive coverage of Unity's C# codebase
  • Regularly updated to reflect the latest Unity engine changes

Cons of UnityCsReference

  • Large and complex codebase, potentially overwhelming for beginners
  • Focuses on engine internals rather than practical game development patterns
  • Requires deep understanding of Unity's architecture to navigate effectively

Code Comparison

UnityCsReference (GameObject.cs):

public sealed partial class GameObject : Object
{
    public Transform transform
    {
        get { return GetComponent<Transform>(); }
    }
    // ... more code ...
}

Unity-Programming-Patterns (ObjectPool.cs):

public class ObjectPool : MonoBehaviour
{
    public static ObjectPool SharedInstance;
    public List<GameObject> pooledObjects;
    // ... more code ...
}

The UnityCsReference example shows Unity's internal implementation of GameObject, while Unity-Programming-Patterns demonstrates a practical game development pattern (Object Pooling) that can be applied in Unity projects.

Pros of EntityComponentSystemSamples

  • Official Unity repository, ensuring up-to-date and accurate implementation of ECS
  • Comprehensive examples covering various aspects of the Entity Component System
  • Demonstrates performance optimizations and best practices for ECS in Unity

Cons of EntityComponentSystemSamples

  • Focuses solely on ECS, not covering other programming patterns
  • May be more complex for beginners due to its advanced nature
  • Requires Unity 2019.3 or later, limiting compatibility with older projects

Code Comparison

EntityComponentSystemSamples:

public class MovementSystem : SystemBase
{
    protected override void OnUpdate()
    {
        float deltaTime = Time.DeltaTime;
        Entities.ForEach((ref Translation position, in Velocity velocity) =>
        {
            position.Value += velocity.Value * deltaTime;
        }).ScheduleParallel();
    }
}

Unity-Programming-Patterns:

public class ObjectPool : MonoBehaviour
{
    public static ObjectPool SharedInstance;
    public List<GameObject> pooledObjects;
    public GameObject objectToPool;
    public int amountToPool;

    void Awake()
    {
        SharedInstance = this;
    }
}

:tea: All Gang of Four Design Patterns written in Unity C# with many examples. And some Game Programming Patterns written in Unity C#. | 各种设计模式的Unity3D C#版本实现

Pros of Unity-Design-Pattern

  • More comprehensive coverage of design patterns, including creational, structural, and behavioral patterns
  • Includes detailed explanations and UML diagrams for each pattern
  • Offers implementations in both C# and TypeScript

Cons of Unity-Design-Pattern

  • Less focused on Unity-specific implementations
  • May be overwhelming for beginners due to the extensive content
  • Some examples lack Unity context or game-specific scenarios

Code Comparison

Unity-Design-Pattern:

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    public static T Instance => _instance;

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

Unity-Programming-Patterns:

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<T>();
                if (instance == null)
                {
                    GameObject obj = new GameObject();
                    obj.name = typeof(T).Name;
                    instance = obj.AddComponent<T>();
                }
            }
            return instance;
        }
    }
}

Both repositories provide valuable resources for learning design patterns in Unity. Unity-Design-Pattern offers a broader range of patterns and more detailed explanations, while Unity-Programming-Patterns focuses more on Unity-specific implementations. The choice between them depends on the user's experience level and specific needs.

Unity Open Project #1: Chop Chop

Pros of open-project-1

  • Comprehensive project structure with multiple scenes and assets
  • Extensive documentation and coding standards
  • Active development and support from Unity Technologies

Cons of open-project-1

  • Larger project size, potentially overwhelming for beginners
  • Focused on a specific game type, less versatile for general learning
  • Steeper learning curve due to complex systems and architecture

Code Comparison

Unity-Programming-Patterns (Singleton pattern):

public class Singleton<T> : MonoBehaviour where T : Component
{
    private static T _instance;
    public static T Instance {
        get {
            if (_instance == null) {
                _instance = FindObjectOfType<T>();
                if (_instance == null) {
                    GameObject obj = new GameObject();
                    _instance = obj.AddComponent<T>();
                }
            }
            return _instance;
        }
    }
}

open-project-1 (ScriptableObject-based event system):

[CreateAssetMenu(menuName = "Events/Void Event Channel")]
public class VoidEventChannelSO : ScriptableObject
{
    public UnityAction OnEventRaised;

    public void RaiseEvent()
    {
        OnEventRaised?.Invoke();
    }
}

The Unity-Programming-Patterns repo focuses on demonstrating various design patterns, while open-project-1 showcases a complete game project structure with more complex systems and architecture.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

# Game programming patterns in Unity

Here you can find a collection of programming (design) patterns in Unity, mainly from the book Game Programming Patterns. These are very useful to better organize your Unity project as it grows because they capture best practices and solutions to commonly occuring problems. You don't have to use them - you should see them as tools in your toolbox. You can also experiment with how they are implemented to fit your specific needs. Some patterns, such as Update, Game Loop, Component, are already built-in into Unity so you are already using them!

Programming patterns can be divided into the following groups:

  1. Architectural patterns. One example is the MVC (Model-View-Controller).
  2. Design patterns. Are more specific than architectural patterns, such as the Singleton.
  3. Anti-patterns. Are a collection of patterns programmers are using to solve problems even though they shouldn't use them because they are ineffective solutions. One example is a "God object," most likely called GameController where you collect everything you might need to make the game work. The problem with such as class is that it will grow in size, which will make it more difficult to maintain, and it will also be difficult to debug because the code doesn't belong together.

Patterns from the book Game Programming Patterns:

  1. Command
  2. Flyweight
  3. Observer
  4. Prototype
  5. Singleton
  6. State
  7. Double Buffer
  8. Game Loop
  9. Update Method
  10. Bytecode
  11. Subclass Sandbox
  12. Type Object
  13. Component
  14. Event Queue
  15. Service Locator
  16. Data Locality
  17. Dirty Flag
  18. Object Pool
  19. Spatial Partition

Other patterns:

  1. Decorator
  2. Factory
  3. Facade
  4. Template

Note that these are not all patterns out there. I recently read a book called "Machine Learning Design Patterns" which includes even more design patterns with a focus on machine learning problems. But I will continue adding patterns as I find them and if they are related to game development.

Sources and Read More

Special Thanks