Convert Figma logo to code with AI

QianMo logoUnity-Design-Pattern

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

4,161
997
4,161
1

Top Related Projects

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

Examples of programming design patterns in Unity C#

An ultra-simplified explanation to design patterns

Attribute Extensions for Unity

Quick Overview

QianMo/Unity-Design-Pattern is a comprehensive collection of design patterns implemented in Unity and C#. It serves as an educational resource for game developers and programmers to learn and apply various design patterns in Unity game development. The repository includes detailed explanations, diagrams, and code examples for each pattern.

Pros

  • Extensive coverage of design patterns specific to Unity development
  • Well-organized structure with clear explanations and visual aids
  • Practical code examples that demonstrate pattern implementation in Unity
  • Regular updates and contributions from the community

Cons

  • Some patterns may be overly complex for beginners
  • Limited documentation in languages other than Chinese
  • Lack of advanced use cases for some patterns
  • Some code examples may need updating for the latest Unity versions

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

This code implements a generic Singleton pattern for Unity components.

  1. Observer Pattern:
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 NotifyObservers()
    {
        foreach (var observer in observers)
        {
            observer.OnNotify();
        }
    }
}

This code demonstrates the Subject class in the Observer pattern, managing a list of observers and notifying them.

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

public class ZombieFactory : EnemyFactory
{
    public override Enemy CreateEnemy()
    {
        return new Zombie();
    }
}

This code shows an implementation of the Factory Method pattern for creating different types of enemies in a game.

Getting Started

To use these design patterns in your Unity project:

  1. Clone the repository: git clone https://github.com/QianMo/Unity-Design-Pattern.git
  2. Copy the desired pattern scripts into your Unity project's Assets folder.
  3. Implement the pattern in your game logic. For example, to use the Singleton pattern:
public class GameManager : Singleton<GameManager>
{
    // Your game manager logic here
}

// Usage in other scripts
GameManager.Instance.SomeMethod();
  1. Refer to the repository's documentation for detailed explanations and best practices for each pattern.

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
  • Well-organized structure with clear explanations and comments

Cons of Unity-Programming-Patterns

  • Less focus on Unity-specific implementations compared to Unity-Design-Pattern
  • Fewer visual aids and diagrams to illustrate pattern concepts
  • Some examples may be simpler or less game-specific than Unity-Design-Pattern

Code Comparison

Unity-Programming-Patterns (Observer Pattern):

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

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

Unity-Design-Pattern (Observer Pattern):

public abstract class Subject
{
    private List<Observer> observers = new List<Observer>();

    public void Attach(Observer observer)
    {
        observers.Add(observer);
    }
}

Both repositories provide valuable resources for learning and implementing design patterns in Unity. Unity-Programming-Patterns offers a broader range of patterns and more detailed explanations, while Unity-Design-Pattern focuses more on Unity-specific implementations and visual representations. The choice between the two depends on the developer's preference for depth vs. Unity-centric examples.

Examples of programming design patterns in Unity C#

Pros of unity-design-patterns

  • More comprehensive coverage of design patterns, including creational, structural, and behavioral patterns
  • Includes practical Unity-specific examples for each pattern
  • Active development with recent updates and contributions

Cons of unity-design-patterns

  • Less detailed explanations and documentation compared to Unity-Design-Pattern
  • Fewer stars and forks on GitHub, potentially indicating less community engagement
  • Some examples may be more complex or harder to understand for beginners

Code Comparison

Unity-Design-Pattern:

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

unity-design-patterns:

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)
                {
                    Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none.");
                }
            }
            return instance;
        }
    }
}

An ultra-simplified explanation to design patterns

Pros of design-patterns-for-humans

  • Written in plain English, making it more accessible to beginners
  • Covers a wide range of design patterns with real-world examples
  • Language-agnostic, applicable to various programming languages

Cons of design-patterns-for-humans

  • Lacks specific Unity implementation examples
  • May not cover Unity-specific design patterns or best practices
  • Less detailed explanations of pattern implementations

Code Comparison

design-patterns-for-humans (PHP example):

interface Lion
{
    public function roar();
}

class AfricanLion implements Lion
{
    public function roar()
    {
        // Implementation
    }
}

Unity-Design-Pattern (C# example):

public abstract class Character
{
    public abstract void Attack();
}

public class Warrior : Character
{
    public override void Attack()
    {
        // Implementation
    }
}

Both repositories provide valuable insights into design patterns, but Unity-Design-Pattern focuses specifically on Unity game development, offering practical examples and implementations tailored for Unity projects. design-patterns-for-humans, on the other hand, provides a more general approach to design patterns, making it suitable for a broader audience across different programming languages and domains.

Attribute Extensions for Unity

Pros of NaughtyAttributes

  • Focuses on enhancing Unity Inspector functionality with attribute-based extensions
  • Provides a wide range of attributes for customizing inspector appearance and behavior
  • Lightweight and easy to integrate into existing Unity projects

Cons of NaughtyAttributes

  • Limited scope compared to Unity-Design-Pattern's comprehensive design pattern examples
  • May require additional setup for complex inspector customizations
  • Less educational value for learning software design patterns

Code Comparison

NaughtyAttributes:

public class Example : MonoBehaviour
{
    [ShowAssetPreview]
    public Texture2D texture;

    [Button("Do Something")]
    private void DoSomething() { }
}

Unity-Design-Pattern:

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

    protected virtual void Awake() { /* ... */ }
}

NaughtyAttributes focuses on attribute-based inspector enhancements, while Unity-Design-Pattern demonstrates various design patterns implementation in Unity. The former improves workflow and inspector usability, while the latter provides a broader understanding of software architecture in game development.

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

Design Patterns Written in Unity3D

This repository is about cool design patterns written in Unity3D C#.

  • Now 23 Gang of Four Patterns have all been finished in Unity3D in this repository.
  • Each pattern contains the corresponding structure implementations, application examples and diagrams. Same way with Naphier/unity-design-patterns, in this repository 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 in Unity3D(with a scene) and a folder or folders ("Example") showing one or more real-world example of using the pattern in Unity3D along with a scene showing it in action. Each pattern folder may contain one or more Example.
  • Game design patterns from book Game Programming Patterns have been partially implemented.

此repo为Unity3D中各种设计模式的实践与运用。

  • 目前已经在Unity中实现了《设计模式:可复用面向对象软件的基础》一书中提出的23种设计模式。
  • 每种模式都包含对应的结构实现、应用示例以及图示介绍。类似Naphier/unity-design-patterns的结构,此repo中的每种模式用单独的文件夹分开。每种模式对应的文件夹中包含了名为“Structure”的子文件夹,里面存放的是此模式在Unity中的使用代码的基本框架实现,而另外包含的Example子文件夹中存放的是此模式在Unity中使用的实际示例。每种框架实现或实例示例实现都包含对应的场景,每种模式文件夹中可能包含一个或者多个Example。
  • 《游戏编程模式》一书中介绍的常用游戏设计模式的Unity版实现也有部分实现。

Contents

I、Gang of Four Patterns in Unity (23种GOF设计模式的Unity实现)

Behavioral Patterns 行为型模式

Structural Patterns 结构型模式

Creational Patterns 创建型模式


II、Game Programming Patterns in Unity (《游戏编程模式》的Unity实现)

Reference resources(参考)