Factory Pattern Basics for Creating Objects

October 20, 2020

Factory Pattern

Unity


Title: Creating Objects in Unity3D using the Factory Pattern
By: Jason Weimann
Youtube – Tutorial
Description: Introductory tutorial to the concept of fatories and the factory pattern in OOP using Unity.


Overview

This tutorial quickly covers the basic idea behind using factories and the factory pattern in OOP through an example in Unity. The overall concept is pretty simple in that it focuses on using an object to create other objects, but they explore putting this idea to use as well as some of the pros and cons of its use.

Notes

Factory: in OOP, an object for creating other objects; a function or method that returns objects of a varying prototype or class (from Wikipedia)
Some of the benefits noted are that this allows you to put all of your object creation into a single place and that you can extend it quite a bit without modifying the underlying logic (following the Open Closed Principle). You do not even need to know the exact type you are expecting to return with the factory since you can return interfaces or abstract classes as well to cover large groups of object types.

Basic Example

In the examples covered, their common practice is to create an abstract class for the type of objects they will want their factory to return. Then any of the objects you want that factory to be responsible for simply inherit from that abstract class. Then the factory class itself is created that uses some method to identify which specific objects to create and uses that information to return the desired objects.

Advanced Example

While not exactly advanced, this example is more in the direction of something that you would actually use. Again the abstract class is created to encompass the objects the factory will return, but this time a Name string with only a getter method is added to this class to help with identification and selection later in the process.

The factory class is much more involved for this example. They create a dictionary that uses the Name values as the keys and the various specific types of the different objects as the values. They then use an Assembly reference to get a reference to each of the different classes inheriting from the initial abstract class throughout the section of the project they are interested in. Using these together they fill the dictionary with all these type references by going through the list gotten from the Assembly reference and adding them to the dictionary.

They then have a method within the factory class to Get an object from it. This requires a string parameter (as this is what is used for the example as the keys for the dictionary created) and uses that to check if that option exists in the dictionary, and if so it creates and returns an instance of that specific type of object.

Final Example

This final example is closest to something they would actually use in a real world situation. The major difference being that they make the factory class into a static class. They use this approach because they do not want to create a new factory everytime they use it, and they did not want to use a singleton pattern because it does not need instantiated in Unity in anyway. This helps make it accessible for anything else to call into it.

While it is not a singleton in and of itself, it does use some similar redundancy approaches to make sure multiple are not created. It has an isInitialized check so that it is only created if it is used at all, and then afterwards it will not create another of itself. It is a bit over redundant, but it works for a quick coverage of the concept in this situation.

Extending the Pattern

One major benefit of this pattern over very basic ways of creating objects covered is how it follows the open closed principle. This is shown after the advanced example by adding another type of object for the factory to return after everything has been built. They create a new class of object again inheriting from that initial abstract class and show that the factory picks up on this and includes it in its options and creates the new object without ever accessing the factory class again. This was cleanly done by just adding its own new class and not modifying any of the previous classes.

Summary

While a very basic concept overall, breaking it down and covering its pros and cons did help me more clearly understand how to look at designing and developing systems to create objects in OOP. This also seems like a nice simple approach to starting to use systems for projects that are not very tiny in size at least, and could be more useful for larger projects when you have a better understanding of how to utilize it in a more complex manner. On a side note this also exposed me to the open closed principle which makes a lot of sense as something to strive for when looking to create more stable projects.

Basics of Dependencies in Unity

October 19, 2020

Dependencies

Unity


Title: Dependencies in Unity
By: Infallible Code
Youtube – Tutorial
Description: Covers the basics of dependencies in programming, with a focus on them within Unity and how they deal with expensive method calls.


Overview

This tutorial nicely breaks down dependencies in programming in general in a very basic and understandable way. This is good for defining it well at the foundational level. It also covers some of Unity’s more expensive method calls and the different ways to cache these results, as well as the different ways to organize and manage dependencies within Unity specifically.

Notes

Dependency: When one object relies on another to function.
The initial example in this tutorial nicely shows how improper code can also hide dependencies. Since they were using FindObjectOfType in the Update method (an extremely expensive and inefficient process), it could be lost that that class was dependent on the Inventory object. Creating a private variable at the class level to hold that data and caching it in the Awake method makes it more much clear, exposing the dependency on the Inventory object.

Dependency Management Techniques

Dependency management techniques are just the ways your classes are accessed by the objects they depend on. There are two major groups for this: internal resolution and external resolution.

Internal Resolution

When an object is responsible for resolving its own dependencies
Accomplished by:

  • Instantiating new instances
  • Using factories or the factory method
  • Using Unity’s built in getters (i.e. GetComponent, FindByComponent)

External Resolution

When an object receives its dependencies from another object
Accomplished by:

  • Constructor parameters
  • Public fields and setter methods
  • Serialized fields

Examples of Using (Or Not Using) Different Methods

Some examples covered:

  • Do NOT use GetObjectOfType if you will have multiple objects of that type
  • For very simple cases, the external serialized field option is common practice
  • Serialized field does not work well if object is loaded dynamically
  • Dynamically loaded objects can usually use an initialization method that acts like a constructor
  • Dynamically loaded objects can also use constructors if they are normal C# classes, but monobehaviours do NOT support constructors

Extenject

Dependency injection is just another word for external resolution. Extenject is a dependency injection framework that manages all the dependencies across your entire project. Extenject can be very useful, but can quickly overcomplicate smaller and simpler projects.

Exploring Unity’s New Input System Further

October 15, 2020

Input System

Unity


Title: How to use the new Input System in Unity3D
By: Coding With Unity
Youtube – Tutorial #1
Description: Indepth tutorial on implementing Unity’s new input system along with programming its use.


Title: New Unity INPUT SYSTEM – Getting Started
By: Dapper Dino
Youtube – Tutorial #2
Description: Quick tutorial using Unity’s new input system and using it with programming.


UPDATE

Title: Unity Input System | How to Use Input Action Assets
By: Infallible Code
Youtube – Tutorial #3
Description: Good all around tutorial for getting started using Unity’s new input system.


Title: Unity Input System Quick Start Guide
By: Unity
Unity – Input System Documentation v.1.0
Description: Unity’s documentation on the new input system.


Overview

I have already tested using the new Unity input system a bit and it seems promising so I wanted to explore it further. These tutorials show it in use on a more in depth level so I expect them to show me some more ways to utilize it properly. The documentation was also included as it is useful to find any methods I may need to keep everything together and working.

Update

I found another good tutorial by Infallible Code that I have added. I think it covers the foundational work of using the new input system better than the other tutorials and gives a better explanation of what the generated class from the input system is actually doing. This makes using it much more sensible.

Resetting Keybindings with New Unity Input System

October 14, 2020

Rebinding Keys

Unity – New Input System


Overview

I have been trying out the new Unity input system to see if it is worth using instead of the older method of building out everything yourself. In this process I wanted to make sure it had a way to rebind keys since this is a gigantic feature to have in almost all games. I was able to find that there are several different ways to change keybindings with the methods found in Unity’s documentation on the new input system found here:

Unity Editing Keybindings for New Input System Version 1.0

The two main methods I am focused on currently are ApplyBindingOverride and PerformInteractiveRebinding. PerformInteractiveRebinding allows for keybinding modification by the player at runtime, and is a quick way to implement a feature commonly found in many games where the player selects an action to change the keybinding for and the game awaits their input to set the new keybinding to that input. I do not think this change is saved inherently however, which is where the other method comes in.

ApplyBindingOverride allows the system to override the default keybinds set by the game originally. So after using PerformInteractiveRebinding methods, that data can be saved to then later be utilized by the ApplyBindingOverride method to reapply the keybind changes every time the game is started. This helps it fall in line with how the feature is utilized in most games in a very convenient and user-friendly way.

Workflow from Aseprite and Photoshop to Unity for Sprite Art

October 7, 2020

Aseprite & Photoshop

Unity Workflow


Title: Improve your WORKFLOW using Aseprite/PS with UNITY
By: Dev!Bird
Youtube – Tutorial
Description: Tutorial showing workflow of creating sprites in Aesprite and Photoshop and importing them to Unity.


Overview

I initially looked into this because Aesprite is a software I have been interested in but haven’t looked to far into it yet. Seeing how easy it is to work with and import your work into Unity here definitely makes me interested in looking to get it if I want to do some more focused sprite work again in the future. Aesprite’s focus on sprite work making it rather simple to use but effective for both still images as well as animation make it a very appealing tool if you do not need the sophistication of Photoshop.

Unity Movement Basics Tutorial

October 6, 2020

Unity

Movement


Title: Move in Unity3D – Ultimate Unity Tutorial
By: Jason Weimann
Youtube – Tutorial
Description: Tutorial for covering the basics of all the different ways to move objects in Unity.


Overview

Movement is something I have worked with a lot in Unity as it is part of basically every project in some way or another. Being such a prevalent topic, I just wanted to make sure I had a good understanding of all the different ways to apply movement so I could pick the best options for specific projects. This tutorial is very basic on every front, but inclusive so I figured it was a good point to make sure I knew all the options. There was not a lot to learn from this tutorial for me, but it did help support some of the approaches I already use.

Tutorial Notes

Transform Based Movement

These approaches to movement deal with directly altering the transform values of an object, such as position and rotation, mathematically through general vector math. This generally the built in physics system and gives very tight and precise controls.

Move Transform Position With Input

This is the first basic approach of altering the transform.position value of objects directly. This used GetKeyDown (which only applies once per press) along with large value changes to create more segmented or tile based movement.

Move Transform Position With Input Limit Movement

Similar to the previous approach but it used a mathematical position check to limit the player’s movement. This kept the player’s positional value from getting too large or too small, which effectively creates boundaries without creating physical boundaries within the game.

Move Transform Position With Input Limit Movement Cleaned

This had the same exact logic as the previous approach, but used different syntax to be more readable. This included a strong focus on using expression body property methods to assign bool variables all within a single line of code.
Example:
private bool ShouldMoveBack => Input.GetKeyDown(KeyCode.DownArrow) && transform.position.z > -1;

Move Transform Position With Input Smoothly

This was the first approach to apply Time.deltaTime to the transform.position value to create much smoother movement. They swapped over the GetKey instead here to continuously apply the movement while the key is pressed. As usual they also applied a move speed value within the movement to help control the size of the incremental steps, and in turn the general speed of the object.

Move Transform Position With Input Smoothly And Rotation

Similar to the previous approach but they added rotation functionality. This was done simply by using Unity’s Rotate method along with a rotation speed value and Time.deltaTime to keep it smooth as well.

Force Based Movement

Move With Force

This started the use of the rigidbody component, which is necessary to use Unity’s physics system. They simply started with the rigidbody.AddForce method to apply force to the object within the physics system and cause it to move. Applying this to a cube however caused it to topple over and give awkward results since the force direction changed with the rotation of the cube.

Move With Force Use Tranform Rotation

To fix some of the issues they were having, they froze the rotation of the rigidbody on all axes so it could not rotate at all. Now when the force was applied the cube simply slid along the ground in the same configuration at all times. To allow it to rotate along the vertical axis of the world, they simply applied an internal transform.Rotate method.

Jump

They simply allowed a strong upwards force to be created with the AddForce method. This section was interesting as they once again covered the benefit of separating your player input reading into your Update method, while your physics application is done in FixedUpdate. They accomplished this by having the inputs in Update simply set bool values, and then FixedUpdate would read those bool values to determine if they should perform an action and what action it should be, and then the FixedUpdate would reset the bools if they performed their action. This helps keep the physics running consistently and smoothly while removing the possibility of inputs being missed or eaten by the player.

Move With Force Transform Rotation Clamp Velocity

This option prevented force from being able to be applied when the velocity of the object passed a certain value. This however is a weird soft cap, because force and velocity are not extremely tied together. Force applies an acceleration which in turn alters the velocity of the object. This means that the velocity can hit a range of different values passed the cap (hence the soft cap) depending on how much force is applied in the instances leading up to the object reaching the velocity cap.

Character Controller

While this is mostly tied to rigidbody components, it felt like its own varied option for movement. This is a component provided by Unity which helps get the basics of a player controller going for you. Along with the basics of setting up movement, it also has some additional features such as slope detection and elevation/step detection.

Navigation Mesh

They really just covered the bare minimums of using a Navigation Mesh to help you move a character around. This also is not something I am focused on using in my next major project so I did not need this section for now.

Animation

This focused on how you can use Unity’s Animation window to provide movement to objects. You create an animation for an object, and then you can select “Record” and save various parameters of the object at various times as key frames for an animation. While the focus was on changing the object’s transform.position values to animate movement, this can be done with any values such as scale or color even. This does not give a lot of variability, but can be useful to quickly get something moving with a repeating pattern in the environment for example.

Summary

As expected there was not a whole lot of new information I got from this tutorial, but it did help me organize the different options in my head better. It also provided yet another point of support on the separation of input and application to movement through the Update and FixedUpdate methods again in the Jump section so that was good to see. That separation is definitely something I will be using moving forward with my own projects.

Unity Create Your Own Keybindings Manager

October 5, 2020

Unity

Input Systems


Title: How to Create a Custom Keybinding Handler for your Unity Game – *Improved*
By: Dapper Dino
Youtube – Tutorial
Description: Tutorial for creating your own basic input manager within Unity.


Overview

The idea behind creating an input manager is to have a flexible and easily accessible tool for both setting up your input system within a game as well as modifying it. This manager should help keep programming associated with the player input more organized and consistent, as well as providing pathways to allowing both the designer and eventually the players options to easily change the inputs to their liking.

Tutorial Notes

Setup

Immediately they create an InputManager class that follows a singleton pattern, but also includes a DontDestroyOnLoad method. This is ok to start, but may be worth looking into editing that if using a more sophisticated multi-scene project setup later on.

Within the InputManager, they created classes to replace some of Unity’s basic input reading methods. These included: GetKey, GetKeyDown, and GetKeyUp.

They then added another class named KeybindingActions, which was a container for a public enum that held references to all the possible actions you may want for the game. For now I decided to just include this enum directly in the InputManager class, but will see if it makes sense to separate later.

Next they add the scriptable object core of this setup, which is named Keybindings. The benefit of using a scriptable object here is that it makes it easy to swap it out with different sets of keybindings (especially with different types of input or controllers).

Building Out InputManager and Keybindings Scriptable Object

Within this scriptable object, they created another class named KeybindingCheck. This provides the connection to setup which keys are tied to which actions. They mention a dictionary could be used here, but they created a list of this serializable class instead so it can easily be seen and modified within the Inspector. This class simply holds data for a KeyBindingActions object and a KeyCode object (to ensure they are connected). The scriptable object then just has a list of these KeyBindingChecks.

They mention if you want the player to be able to set their own keybindings you technically just need to edit the scriptable object and this will modify the keybindings. However, scriptable object changes only remain if they are done in the inspector, so you would also need to save that data somewhere else if you had a game where you want the player to be able to set their keybindings once and have the same setup each time they close and reopen the game, which would be the standard implementation.

With that setup, they go back to fill out the methods within the InputManager which effectively replace those provided by Unity. Each of them follow the same pattern seen here in the GetKeyDown replacement method:

public bool GetKeyDown(KeyBindingActions key)
{
foreach (KeyBindings.KeyBindingCheck keyBindingCheck in keybindings.keyBindingChecks)
{
if (keyBindingCheck.keyBindingAction == key)
return Input.GetKeyDown(keyBindingCheck.keyCode);
}

return false;
}

So effectively whenever you would use GetKeyDown for example, you use this InputManager.GetKeyDown method and pass in one of the enum options you have provided as a parameter (i.e. Jump, Crouch) and it searches through the list of KeyBindingCheck objects you have in the KeyBindings scriptable object and if it finds that enum in that list, it returns the Unity base input method (i.e. GetKeyDown here) with the corresponding keyCode you have associated with that enum as its input parameter.

Summary

I like that this method allows for the use of easily accessible and modifiable enums that are specifically chosen for your game when it comes to programming the input of your game, but I am concerned how efficient this is since it appears to add small extra checks with every single input from this user. While small, this is an extremely common action that will be used thousands and thousands of times easily in normal gameplay so I wonder if it ends up being worth the cost. This method does also allow you to edit the keybindings at runtime and because it is with a scriptable object, the changes are actually saved even when exiting play mode.

Newer Unity Input System

October 5, 2020

Unity

Input Systems


Title: NEW INPUT SYSTEM in Unity
By: Brackeys
Youtube – Tutorial
Description: Tutorial for using Unity’s newer input system.


Overview

This setup uses Unity’s improved new input setup system. It provides a nice way to setup your inputs more specifically without directly going into the Project Settings -> Input Manager window. The user starts with a blank slate and adds actions to this input manager asset to match up with all the actions they will want in the game.

From this tutorial they obtained the tools to use this new input system through a project on github, but now it is available as a standard package within Unity simply named Input System. It however mentions that the backend has been modified (I am using Unity version 2020.1.5f1 currently when testing this) so I am keeping an eye out for any problems it may cause.

Tutorial Notes

There are three major sections to this input system: Action Maps, Actions, and Properties. The action maps appear to be like keybinding sets, so you can save entire different sets of actions with their own keybindings to each map you create. Then the actions are the core focus, where actions can be named and keybindings can be set, as well as which types of controllers are used. Finally the properties section allows for more detailed additions to each action such as other modifiers to apply to the input when used as well as the type of action.

After filling this out to the desired result, there is an option to “Generate a C# Class” from this new input system you have created. This provides you with the proper tools to utilize the asset you created within your programming system yourself. The context is a bit more awkward as it uses events, so you have to assign methods to them when using them in your own programming. They set this up in the Awake method for example:

controls.Player.Shoot.performed += _ => Shoot()

controls is the name of the InputMaster object (which is what they named the generated C# file from the input system), Player is the name of the action map, shoot is the name of the action from the input system, performed is a subset of that action, and finally Shoot is the method being subscribed to that event. The underscore is simply a place holder used for this programming syntax so it is necessary but I am unsure exactly why the syntax is like that.

I was then having an issue following the tutorial because they simply made controls (their InputMaster object) public so they could drag/drop the input system asset itself directly into the component so they were connected and running. When I did this the InputMaster object did not show up in my Inspector, even when made public. To get it to work at all, I found that I just needed to assign a new InputMaster to controls in the Awake method. I found that in the documentation provided here: Unity New Input System Manual

I then found that natively you could not use both the old input system and the new input system at the same time. So while this did get the new input system working and I could jump (which was the only action I assigned for testing), I could not move horizontally at all as the inputs for that just did not work anymore. Exploring the documentation further, I did find that you can switch back and forth between the old and new input system, as well as activate both at the same time, in the: Project Settings > Player, under: Active Input Handling. Upon setting that to both, I could move horizontally (with the old inputs) and jump (with the new inputs).

Installation Guide here: Unity New Input System Installation and Setup Documentation

Summary

This approach seems promising for setting up complex keybinding setups where you also want multiple devices. It does provide the base benefit of not needing to use strings with the input system anymore when doing the programming so that is a large benefit already. I would have to explore how to edit keybindings at runtime with this setup to see if it is a good final approach for this system that would also support letting the player set their own keybindings.

Brackeys 2D Movement and Melee Combat Tutorials – 2D Movement

September 30, 2020

Unity

2D Movement


Title: 2D Movement in Unity (Tutorial)
By: Brackeys
Youtube – Tutorial #1
Description: Tutorial for using a simple Unity player controller.


Title: MELEE COMBAT in Unity
By: Brackeys
Youtube – Tutorial #2
Description: Tutorial for setting up basic melee combat with a 2D player controller.


Overview

I started with the Melee combat tutorial but it referenced the movement tutorial for how they setup the starting movement and animation so I wanted to move back to them just to make sure I was starting in a similar spot. The player controller made in the 2D movement tutorial is actually pretty bad unfortunately, but I still wanted to use this melee combat tutorial as a base point for something that is workable but not amazing just to get an idea of how to approach combat.

2D Player Movement – Tutorial #1

While overall not a great tutorial, it did support some concepts I have come across. They separated the player input functionality and the actual movement application into the Update and Fixed Update methods respectively, which is a solid approach I have seen more and more in my search for information on player controllers now. However, all of the Fixed Update work was basically already done in a Player Controller script they gave you, so it really just covered programming the script responsible for receiving player input and passing it on to the movement logic.

To make matters worse, the given script does not even work particularly well. Its checks for the ceiling and the ground can give weird results unless at good ranged values which can prevent your player from crouching or jumping, or getting out of crouch at times. Then when air control is turned on, there is a bug where the character automatically crouches in midair (which removes their upper hitbox) simply from them jumping into objects as the ceiling sensor activates and automatically makes them crouch in the air.

I was able to fix the midair crouching bug by adding an extra check in the tutorial given script to also ensure the player was grounded before making crouch true. This led to another interesting aspect of the tutorial with the separation of input and actual player movement because the movement was receiving information from the input such as “is crouch being pressed” and then would use that information and check the surroundings (such as if they are under a ledge) to determine whether they could actually move out of crouch or not. This was just an interesting way of separating the input logic from the actual player control logic and is good to keep in mind for an input buffering system.

After fixing the bugs and messing with adding some animation similar to what they already have at the start of the melee combat tutorial, I did not have time to move on to that one. I will look into completing that next with my decent player controller in place now with most of the animations.

Unity Custom Keybinding Manager

September 29, 2020

Unity

Keybinding Manager


Title: How to Create a Custom Keybinding Handler for your Unity Game – *Improved*
By: Dapper Dino
Youtube – Tutorial
Description: Tutorial for setting up an input manager scriptable object in Unity.


Overview

I was looking for a nicer way to control inputs and controls when setting up a Unity project other than the very basic way of listing out all the specific key codes in the user scripts themselves or using fragile string references when tying it to Unity’s natural input manager. Initially I came across this creator’s first attempt at setting up a keybinding handler (hence the *Improved* tag on the title of this tutorial) but was not as interested in it since they still used strings and I thought an enum implementation would be better, but lo and behold, the same creator had actually improved their system a year later with an enum system like I was imagining.

While maybe not perfect, I do still like this overall implementation better than just using Unity’s natural tools for sure. Adding the enum setup removes the necessity of typing in direct and exact strings in your code which is great for reliability, while also making it easy to change key bindings in the scriptable object itself during develop. Having a system like this is also a good start for a truly accessible product on release that allows users to set their own keybindings, which is standard in many games.