Convert Figma logo to code with AI

Naphier logounity-design-patterns

Examples of programming design patterns in Unity C#

1,126
161
1,126
3

Top Related Projects

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

: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#版本实现

Quick Overview

Naphier/unity-design-patterns is a GitHub repository that provides examples of common design patterns implemented in Unity using C#. It serves as a practical resource for Unity developers to learn and apply various design patterns in their game development projects.

Pros

  • Offers practical implementations of design patterns specifically tailored for Unity
  • Includes a wide range of design patterns, covering creational, structural, and behavioral categories
  • Provides clear, well-commented code examples for each pattern
  • Regularly updated and maintained, ensuring compatibility with recent Unity versions

Cons

  • May not cover every possible design pattern or variation
  • Some examples might be simplified and may need adaptation for complex real-world scenarios
  • Requires a basic understanding of C# and Unity to fully grasp the concepts
  • Limited documentation outside of code comments

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, ensuring only one instance of a MonoBehaviour exists.

  1. Observer Pattern:
public interface IObserver
{
    void OnNotify();
}

public class Subject : MonoBehaviour
{
    private List<IObserver> observers = new List<IObserver>();

    public void AddObserver(IObserver observer)
    {
        observers.Add(observer);
    }

    public void RemoveObserver(IObserver observer)
    {
        observers.Remove(observer);
    }

    protected void Notify()
    {
        foreach (IObserver observer in observers)
        {
            observer.OnNotify();
        }
    }
}

This example demonstrates the Observer pattern, allowing objects to subscribe and receive notifications from a subject.

  1. Factory Method Pattern:
public abstract class Enemy : MonoBehaviour
{
    public abstract void Attack();
}

public class EnemyFactory : MonoBehaviour
{
    public Enemy CreateEnemy(string enemyType)
    {
        switch (enemyType)
        {
            case "Goblin":
                return gameObject.AddComponent<Goblin>();
            case "Orc":
                return gameObject.AddComponent<Orc>();
            default:
                return null;
        }
    }
}

This code showcases the Factory Method pattern, providing a way to create different types of enemies without specifying their exact classes.

Getting Started

  1. Clone the repository: git clone https://github.com/Naphier/unity-design-patterns.git
  2. Open the project in Unity (preferably using the version specified in the repository)
  3. Navigate to the desired pattern's scene in the project hierarchy
  4. Study the implementation in the scene and associated scripts
  5. Experiment with the patterns by modifying the existing code or creating new implementations

Competitor Comparisons

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

Pros of Unity-Programming-Patterns

  • More comprehensive coverage of design patterns, including structural and behavioral patterns
  • Includes practical examples and use cases for each pattern in Unity
  • Regularly updated with new patterns and improvements

Cons of Unity-Programming-Patterns

  • Less focus on performance optimization compared to unity-design-patterns
  • May be overwhelming for beginners due to the large number of patterns covered

Code Comparison

unity-design-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();
                    _instance = obj.AddComponent<T>();
                }
            }
            return _instance;
        }
    }
}

Unity-Programming-Patterns:

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;
        }
    }
}

Both repositories implement the Singleton pattern similarly, with Unity-Programming-Patterns adding a name to the created GameObject for better organization.

: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 additional categories like Architectural, Concurrency, and Game Programming patterns
  • Includes detailed explanations and UML diagrams for each pattern, enhancing understanding
  • Provides both C# and TypeScript implementations for broader applicability

Cons of Unity-Design-Pattern

  • Less focused on Unity-specific implementations compared to unity-design-patterns
  • May be overwhelming for beginners due to the extensive coverage of patterns

Code Comparison

Unity-Design-Pattern (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;
        }
    }
}

unity-design-patterns (Singleton pattern):

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    public static T Instance {
        get {
            if (_instance == null) {
                _instance = (T)FindObjectOfType(typeof(T));
                if (_instance == null) {
                    var singletonObject = new GameObject();
                    _instance = singletonObject.AddComponent<T>();
                    singletonObject.name = typeof(T).ToString() + " (Singleton)";
                }
            }
            return _instance;
        }
    }
}

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

  • Focused solely on ECS, lacking coverage of other design patterns
  • May be overwhelming for beginners due to its complexity and advanced concepts
  • 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-design-patterns:

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    public static T Instance
    {
        get { return _instance; }
    }
    protected virtual void Awake()
    {
        _instance = this as T;
    }
}

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

Welcome to Unity Design Patterns

Examples of programming design patterns in Unity3D C#

Thanks to Robert Nystrom's Game Programming Patterns and the examples found on Rivello Multimedia's website. Each pattern is contained in a separate folder. Inside these are a folder ("structure") to show what classes are used in the pattern's structure and a folder ("example") showing a real-world example of using the pattern in Unity3D along with a scene showing it in action.

As these are accomplished I plan to do a blog article on each. Once the articles are done they will be referenced in each pattern's readme.md.

Details on each pattern can be found in the Readme.md file in each pattern's folder.

Patterns done:

Contributors Welcome

Please check out contributors.md if you'd like to help out with this project. It will take me forever to do all of these on my own and I'd love to have some help!

Patterns to do:

  • Prototype
  • Singleton (Monobehaviour derived and non-derived)
  • Adapter
  • Bridge
  • Composite
  • Facade
  • Proxy
  • Chain of Responsibility
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor