techwrath-logo-2023

Introduction to Design patterns being used in unity

Design patterns are solution to most commonly error in software design. They are plans that can be taken and modified to solve a specific problem in the code. Design patterns are formalized best applies that the programmer can use to solve common problem when design an application.

Commonly used design patterns in unity

  1. Command pattern
  2. Flyweight pattern
  3. Observer pattern
  4. Singleton
  5. State pattern
  6. Update method
  7. Event queue
  8. Object pool
  9. Spatial partition

Command pattern:

In object –oriented programming, the command patterns a interactive design pattern in which an object is used to summarize all the information need to achieve an action or generate an event at a later time.

One example where the command pattern is useful is when you let the player change the button meaning when you have set the button of fire to A but the player want to use U to fire

Example:

Public abstract class Command

{

Public abstract void Execute ();

}

Public class FireWeapon : Command

{

public override void Execute()

{

FireTheWeapon();

}

}

public class DoNothing : Command

{

public override void Execute()

{

}

}

Command buttonU = new FireWeapon();

Command buttonA = new DoNothing();

if (Input.GetKeyDown(KeyCode.U))

{

buttonU.Execute(); //Will now call the FireTheWeapon() method in the Execute() method in the FireWeapon class

}

if (Input.GetKeyDown(KeyCode.A))

{

buttonA.Execute(); //Will do nothing because the Execute() method in DoNothing class is empty

}

Flyweight pattern

In programming, flyweight is a design pattern. A flyweight is an object that reduces memory use by distributing as much data as possible with other alike Objects.

Example:

So we are here going to use Animals with thousands of eyes, arms, and legs. So we need an animal’s class that describes animals

//Flyweight design pattern main class

namespace FlyweightPattern

{

Public class Flyweight : MonoBehaviour

{

//The list that stores all animals

List<animals> allAnimals = new List<animals>();

List<Vector3> eyePositions;

List<Vector3> legPositions;

List<Vector3> armPositions;

void Start()

{

//List used when flyweight is enabled

eyePositions = GetBodyPartPositions();

legPositions = GetBodyPartPositions();

armPositions = GetBodyPartPositions();

//Create all animals

for (int i = 0; i < 10000; i++)

{

animals newAnimals = new animals();

//Add eyes and leg positions

//Without flyweight

newanmals.eyePositions = GetBodyPartPositions();

newanimal.armPositions = GetBodyPartPositions();

newanimal.legPositions = GetBodyPartPositions();

allaniamals.Add(newAlien);

}

}

//Generate a list with body part positions

List<Vector3> GetBodyPartPositions()

{

//Create a new list

List<Vector3> bodyPartPositions = new List<Vector3>();

//Add body part positions to the list

for (int i = 0; i < 1000; i++)

{

bodyPartPositions.Add(new Vector3());

}

return bodyPartPositions;

}

}

}

If you add the Flyweight.cs to an empty game object and then open the profiler, press play, click on the Memory box, you will see this image:

In here you should pay attention to mono, which according to unity is the “ total heap size and used heap size used by managed code this memory is rubbish collected.\” It\’s currently at 0.57 Gb, which is the number we are going to lower with the flyweight pattern.

After Applying flyweight

To add the flyweight pattern we will just assume that all animals has same body type position. It does not look realistic but this is just a test to check the flyweight pattern so change the code to something like this

//Add eyes and leg positions

//Without flyweight

//newAlien.eyePositions = GetBodyPartPositions();

//newAlien.armPositions = GetBodyPartPositions();

//newAlien.legPositions = GetBodyPartPositions();

//With flyweight

newAlien.eyePositions = eyePositions;

newAlien.armPositions = legPositions;

newAlien.legPositions = armPositions;

So now we generate the profiler again to check the difference between code with flyweight pattern and with out flyweight pattern.

So the memory use has gone to 15.3MB from 0.57Gb

Observer pattern:

The observer pattern is a software design pattern in which an object calls the subject, keeps a list of its children, called observers and informs them automatically of any state of changes frequently by calling one of their methods.

So the basic idea is that you should use the observer pattern when you need many objects to receive an update when another object changes. The observer pattern is essentially the interaction backbone of countless programs and app frameworks.

One example is when you need to add achievements in your game. This might be hard to apply if you have several achievements each has to be unlocked by a different behavior. But it is much easier to apply if you know the observer pattern

Singleton pattern:

The singleton pattern is a software design pattern in which you can create instance of the class. This pattern is basically used when you want to use a single script in different scenes  .for example you want to make a ads controller that will show ads in different scene instead of make a game object of ads controller in all scene you can use the first ads controller in all the scene and call it in different script

Example:

Public static Adscontroller instance; // we have made the instance of the ads controller script

void Awake(){

makeSingleton();

}

void makeSingleton(){

if(instance != null)

{

destroy(gameobject);

}

else{

instance = this;

DontDestoryOnLoad(gameObject);

}

State pattern

The state pattern is a behavioral software design pattern; this pattern is used in computer programing to summarize variable behavior for the same object based on its inner state

Example

Its normal to use enums when coding a state machine in c#  and its looks like this in our bike example :

enum BikeFSM

{

Forward,

Brake,

Reverse,

Park

}

//Default state

BikeFSM BikeMode = BikeFSM.Park;

//And then you change the state with something like

if (BikeMode == BikeSM.Park && IsPressingracel())

{

BikeMode = BIkeFSM.Forward;

}

else if (BIkeMode == BikeFSM.Forward && IsPressingBrake())

{

BIkeMode == BIkeFSM.Brake;

}

//…and soon

Update Method:

  This design pattern is unity’s Update () method. The idea is that the game world has a group of objects whose behavior has to be updated each frame. Each of these objects has to have an updated method.

Event queue:

This design pattern is same as the observer pattern and it is used to high-level communication between game systems that want to stay decoupled. You can also use it for playing sounds effects by mixing the sound effects before adding them to the list if they are the same (and then playing only the loudest).

Object pooling:

This design pattern is used unity when you want use a single object multiple times. For example if you have a gun that fire bullets then you should reuse the bullet instead of destroying them and creating new ones. So when a bullet has hit target you can disable the bullet when it has completed its action .you can fire a new bullet you can active the old bullet and use it again.

Spatial partition:

When making a game you will mostly need a map to see for the enemies that are close to the player. The usual way is to store all the enemies in a list, and search through them and calculate the distance between enemy and player and show the one close to player

Example:

GameObject FindClosestEnemySlow(GameObject soldier)

{

GameObject closestEnemy = null;

float bestDistSqr = Mathf.Infinity;

//Loop through all enemies

for (int i = 0; i < enemySoldiers.Count; i++)

{

//The distance sqr between the soldier and this enemy

float distSqr = (soldier.transform.position – enemySoldiers[i].transform.position).sqrMagnitude;

//If this distance is better than the previous best distance, then we have found an enemy that\’s closer

if (distSqr < bestDistSqr)

{

bestDistSqr = distSqr;

closestEnemy = enemySoldiers[i];

}

}

return

Conclusion:

You learned how design patterns make software development simpler by offering you with a toolbox of solutions to common problems you face in object-oriented design. But the knowledge is like a vast sea so there is always something new to learn.

11 Comments on Introduction to Design patterns being used in unity

    Winfred
    March 17, 2021

    Hello there, just became aware of your blog through Google,
    and found that it is really informative. I'm going to watch out for brussels.

    I'll be grateful if you continue this in future. A lot of people
    will be benefited from your writing. Cheers!

    0
    0
    my web hosting
    August 28, 2021

    Wow, that's what I was seeking for, what a data!
    existing here at this weblog, thanks admin of this site.

    0
    0
    asmr or
    September 5, 2021

    Have you ever thought about including a little bit more than just your articles?

    I mean, what you say is important and everything. Nevertheless think of if you added some great visuals or videos to
    give your posts more, "pop"! Your content is excellent but with images and clips,
    this site could certainly be one of the most beneficial in its niche.
    Awesome blog!

    0
    0
    Faustino Tempelton
    October 23, 2021

    At this time it looks like Expression Engine is the best blogging platform available right now. (from what I've read) Is that what you are using on your blog?|

    0
    0
    Rivka Chilton
    October 24, 2021

    I love what you guys are up too. This kind of clever work and coverage! Keep up the great works guys I've included you guys to blogroll.|

    0
    0
    Elmer Macaskill
    October 25, 2021

    If you desire to grow your knowledge just keep visiting this web page and be updated with the hottest news update posted here.|

    0
    0
    Hyon Lujano
    October 25, 2021

    Everyone loves what you guys tend to be up too. Such clever work and exposure! Keep up the superb works guys I've added you guys to my own blogroll.|

    0
    0
    Jame Padua
    October 26, 2021

    My spouse and I absolutely love your blog and find nearly all of your post's to be just what I'm looking for. can you offer guest writers to write content for you personally? I wouldn't mind creating a post or elaborating on a few of the subjects you write in relation to here. Again, awesome web log!|

    0
    0
    Dorothy Smsith
    October 30, 2021

    Thanks to my father who told me concerning this website, this web site is actually awesome.|

    0
    0
    Cassy Sanks
    October 31, 2021

    Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!|

    0
    0

Leave A Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.