Modding Monster Train – Harmony Reverse Patches

July 14, 2021

Modding with Harmony

Monster Train


Title:
Harmony ParDeike – Reverse Patch

By:
Harmony


Harmony – Documentation

Description:
Harmony documentation on patching with the Reverse Patch.


Overview

I was investigating ways to use Harmony to access private methods and fields from classes within the Unity target game itself, Monster Train in this case. One of the first direct options I came across was using reverse patches.

Basics of the Reverse Patch

“A reverse patch is a stub method in your own code that ‘becomes’ the original or part of the original method so you can use that yourself.”

    Typical use cases:

  • easily call private methods
  • no reflection, no delegate, native performance
  • you can cherry-pick part of the original method by using a transpiler
  • can give you the unmodified original
  • will freeze the implementation to the time you reverse patch

Implementation

After seeing its first use case being calling private methods, I thought this would be a perfect tool to use. As far as I have found, it appears to need a reference to an instance of the object that the private method belongs to. This has proved rather troublesome. While the setting up of the reverse patch has appeared to work and run, it is running into other issues that require further research.

The class I am trying to access is a Unity Scriptable Object, and has no easy way to directly access the existing instance (that I have found so far). I tried circumventing this by creating my own instance to work from, but that has its own issues. The new instance, if it is even being generated properly, is not intialized in any way and is missing integral references, such as to the AllGameData, which are also difficult to inject into the instance. This is again because it is a Unity Scriptable Object, so most fields are private but serialized, so they are very protected and only exposed in the Unity Inspector to make the necessary references I am missing in a newly generated instance.

via Blogger http://stevelilleyschool.blogspot.com/2021/07/modding-monster-train-harmony-reverse.html

Observer Pattern in Unity with C# – by Jason Weimann

April 22, 2021

Observer Pattern

Game Dev Patterns


Title:
Observer Pattern – Game Programming Patterns in Unity & C#

By:
Jason Weimann


Youtube – Tutorial

Description:
Introduction to the observer pattern and implementing it in Unity through C#.


Overview

This tutorial covers the basics of the observer pattern in game development with two ways of implementing it in Unity. The first approach is relatively simple just to establish the concept, whereas the second approach uses events with C# to create a more flexible system.

Observer Pattern Basics

An object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes (usually by calling one of their methods)

Example Uses in Games:

UI elements updating when data behind them changes

Achievement systems

Implementation #1: Inheriting Observer and Subject Classes

Observer Class:

Abstract class your observers will inherit from

OnNotify() method that accepts a value and notification type


Subject Class:

Abstract class your subjects will inherit from

Hold information on their list of observers they report to

RegisterObserver() method to add Observers to list of those reporting to

Notify() passes a value and notification type on to all the observers they report to in their list, in turn calling their OnNotify methods with the passed on data

This example gets the point across, but is not particularly well suited for Unity or C# projects. Requires a base class on all observers and subjects (although could possibly be changed to using an interface system).

Implementation #2: Using Events

Subject objects create a ‘static event Action‘, which they then call when the requirements are met.

Observer objects have their own methods to perform when those same requirements are met, and they are connected by having the observers subscribe their relevant methods to that same ‘static event’.

This reduces the direct coupling between the observers and subjects, as well as any other objects involved. Should profile this as calling events every frame can start to lead to performance loss. As always, also need to be careful to properly unsubscribe methods from events when needed (such as when deactivating or destroying objects).

via Blogger http://stevelilleyschool.blogspot.com/2021/04/observer-pattern-in-unity-with-c-by.html

Basics of System.Random in C#

February 14, 2020

System.Random Methods

C# and Unity

Random Class (from Microsoft)

Information – Link

By: Microsoft


General Methods Looked Into

Random.Next

This selects a random integer either between 0 and maximum value, or between two different designated values.

Random.NextDouble

This generates a random floating point value between 0.0 and 1.0. This is the main one I will be looking to use since I have a lot of parameters where floating point values make sense, however since it only returns values between 0.0 and 1.0 specifically, I will have to just use it as a random multiplication factor.

Random.NextByte

This requires an input of an array of bytes. It will then fill that array with random byte values.

Why I am Investigating

My thesis project uses a lot of random values with its focus on varied procedural content generation, but I want to control the randomness a bit more with the implementation of a seeding system. A tutorial I did a while back on cellular automata uses a very basic seeding system for its randomization that I was looking to copy. It centers around this line where seed is just a string variable that can be set in the editor:
System.Random psuedoRandom = new System.Random(seed.GetHashCode());

As long as the seed string is the same and a value is randomly selected using this Random variable psuedoRandom, the value selected for that particular case will remain the same over multiple plays of the program. This helps provide control and consistency to the random system generation so if I find good samples they can be recorded by their seed string.

Random.Next and Random.NextDouble are going to be the main two that I use, as they help generate random ints or random floating point values (doubles that can be cast as floats if necessary). Random.Next will be very useful in cases where I am generating a specific number of objects, where Random.NextDouble will be used to generate the varied values for parameters that are within specific ranges (such as the length or size of an object). As noted previously Random.NextDouble can only specifically generate values between 0.0 and 1.0, so it will be used as a random multiplication factor to get the results I need.

Unity Event Systems: Introductory Research

December 17, 2019

Unity Event Systems

Basics, Setup, and Tutorials

ADDENDUM: An EVEN MORE AWESOME Event System, by viewers!

Link – Tutorial 1

By: quill18creates


C# Events

Link – Tutorial 2

By: Jonathan Weinberger {ON Unity Learn Premium}


Tutorial 1

They created a public abstract class, Event, that all types of events will just inherit from. This helps keep all your events nice and similar, as well as making sure they all have key methods such as those necessary for registering and unregistering listeners. Since each event type is its own version of this base event, they can each hold a different collection of listeners, which makes sense since you only want certain behaviors to happen when certain events happen (such as a unit dying).

Inheritance and Static Fields in C#

This was an interesting interaction that I did not know it worked this way. When a base class in C# contains a static field, and then you create a new class that inherits from this class, it actually creates its own separate and unique version of that static field (as opposed to their just being one overall static field contained in the base class for all classes that inherit it). This has pros and cons. The pros are that it is helpful when you want the derived classes to be able to hold data only amongst themselves. The cons are obviously that you will have to do something a bit extra if you want something to contain all the information from all derived classes from that original base class.

Tutorial 2

This is just a very basic intro to events in C# I found on Unity Learn premium. This was beneficial to just cover some basic rules of events in general again.

General Events Notes

  • allow us to create broadcast system so other objects can subscribe/unsubscribe
  • need delegate type
  • will cause an error if it’s null when called
  • helps classes be self contained (since they do not rely on communication directly with another object)
  • every instance of an object that wants to be subscribed to the event must make sure that it itself subscribes
  • have inherent security (as opposed to delegates)
  • General Rule: always have an unsubscribe for every subscribe

Final Notes

Unity Learn actually has a ton of information, tutorials, and practice for learning about events, so I will most likely look to follow some of them in the future. They range from a few more really basic ones such as the one I just checked out, to more challenging ones, and even advanced ones that are much more project based as well. I really think this type of system will be useful for my current personal project, so I want to understand it well in an effort to properly utilize it.

Programming A* in Unity

November 14, 2019

A* Programming

Unity

A* Pathfinding (E01: algorithm explanation)

Tutorial #1 – Link

By: Sebastian Lague


Unity – A Star Pathfinding Tutorial

Tutorial #2 – Link

By: Daniel


Unity3D – How to Code Astar A*

Tutorial #3 – Link

By: Coding With Unity


I have used A* before, but I would like to learn how to setup my own system using it so that I can make my own alterations to it. I would like to explore some of the AI methods and techniques I have discovered in my AI class and use that to alter a foundational pathfinding system built with A* to come up with some interesting ways to influence pathfinding in games. I would eventually like to have the AI “learn” from the player’s patterns in some way to influenece their overall “A* type” pathfinding to find different ways to approach or avoid the player.

Colon Uses in C#: Chain Constructors

August 20, 2019

Colon

In C# Language

StackOverflow – In C# what category does the colon “ : ” fall into, and what does it really mean?
C# Corner – Constructor Chaining In C#

I was reading over some C# code and came across a weird use of a colon and decided to look into some of its uses to get a better understanding of when it is being used. The stack overflow answer I came across was the most inclusive and helpful for looking into it more, as it described the colon as a “simple syntactic symbols, like [] or {}” as opposed to being a type of operator.

The case I was looking at using the colon appeared to be a chain constructor setup. A colon can be used to call another constructor (or the base constructor class) prior to the current one. This led to the next link when I searched for more help on constructor chaining.

Examples:

public Foo() : base() { }

public Foo(int bar) : this() { }

public class mySampleClass
{
public mySampleClass(): this(10)
{
// No parameter constructor method.// First Constructor
}

public mySampleClass(int Age)
{
// Constructor with one parameter.// Second Constructor}
}
}

C# LINQ Extension Methods

May 23, 2019

C# LINQ Extension Methods

Microsoft – => operator (C# Reference)
Youtube – C# Tutorial 13 LINQ Extension Methods

By: Derek Banas

I was working on a tutorial for GPU Instancing and dynamic batching a while ago to look into some ways to visually instantiate a lot of objects in Unity without overloading the computer and there was a lot happening in the code I was unfamiliar with. The biggest parts that stood out were the ” => ” operator along with some list and array methods.

The => operator was used within a list method called “Select”, so I started looking into both of those. The name of the => operator is the lambda operator. The simplest aspect seems to be that it’s a function with the parameters on the left side and the performing function on the right side. IT also seems to be used a lot with LINQ, which I am unfamiliar with.

Unity Programming – Delegates and Events

March 18, 2019

Unity Programming – Delegates and Events

Tutorials and Definitions

Youtube – Delegates – Unity Official Tutorials

By: Unity

Youtube – Events – Unity Official Tutorials

By: Unity

The scene management update has made significant progress, I am now currently loading and unloading the proper scenes at the proper times. The timing of the loading and unloading is still off however, as well as the fading animation timing is very strange. The fading error makes sense since I have the scene transition and the fading in the same method currently, so I will look to separate those and time them properly with IEnumerators. I was also told today that OnSceneLoad delegates would be a very helpful feature for me to look into to fix all my scene loading timings.

The basic IEnumerator timing I was also suggested to look into was: wait until animation is done, wait until next scene is loaded, then unload scenes to be unloaded.

Upon investigating delegates, I found that they are a very big part of coding in general. Looking into delegates also led me to events, which are somewhat like a specialized type of delegate. I believe understanding both of these will be very beneficial to my current scene loading issues, as well as being very useful for many other game programming purposes, so I wanted to take the time to better understand them before rushing back to my scene development needs.

TERMINOLOGY

Delegates

Delegates: Simply a container for a function that can be passed around, or used as a variable. Just like variables, delegates can have values assigned to them and can be changed at runtime. The difference is that while variables contain data, delegates contain functions.

First you create a delegate template with the delegate keyword. This dictates what types of methods we can assign to the delegate. Similar to a function, a delegate has: a return type, a name, and a parameter list. The methods you want to add to this delegate must have both the same type of return type and parameter list. You then have to declare a member variable with the type of the delegate you created.
Example:
delgate void MyDelegate(int num)
MyDelegate myDelegate

Then, you can either assign methods to the delegate as values directly, or add/remove methods from the delegate with the += or -= operators respectively. Adding several methods to a single delegate is called multicasting.

The example from the Unity Official Tutorial I linked is as follows: using UnityEngine;
using System.Collections;

public class MulticastScript : MonoBehaviour
{
delegate void MultiDelegate();
MultiDelegate myMultiDelegate;


void Start ()
{
myMultiDelegate += PowerUp;
myMultiDelegate += TurnRed;

if(myMultiDelegate != null)
{
myMultiDelegate();
}
}

void PowerUp()
{
print (“Orb is powering up!”);
}

void TurnRed()
{
renderer.material.color = Color.red;
}
}

This shows the potential of a multicast delegate. On start, the PowerUp and TurnRed methods are both added to the myMultiDelegate delegate (which is possible since both methods have return type of void with no parameter list, just as the delegate does). Now anytime afterward, if the myMultiDelegate is called, it will perform all of the methods added to it (in this case both PowerUp and TurnRed). It is also noted that if you want to remove methods from myMultiDelegate, just use the -= operator along with the name of the method you want to remove.

One final note was that attempting to use a delegate that has not been assigned anything will cause an error. In this case, a delegate will have its default value, which is null. This is why they show in the tutorial that it is good practice to check that the delegate is !null before attempting to use it.

Events

Events: specialized delegates that are useful when you want to alert other classes that something has happened. An event can be thought of as a broadcast system. Any class interested in an event can subscribe methods to it. When that specific situation occurs, the event is invoked, which calls the methods of the subscribed classes. So an event is just like a delegate classes can send methods to, and then when that event is called, all of those methods will happen.

In the Unity Event tutorial I linked, they start by creating an EventManager script they place on the camera (this might be different with Event Systems now, this is an old tutorial). They then create a public delegate, which is then the type used for the public static event they create. So it appears that an event might be something similar to a list of delegates, and you add the type of delegate to it to determine what types of methods you can subscribe to this event. The tutorial then ties the event to a button press. Now any time this button is pressed, every method subscribed to the event will be invoked.

To show the broadcasting nature of events, there are two separate game objects with two separate scripts attached to them that subscribe different methods to the same event. They also show the proper fundamental practice of dealing with events. The scripts subscribe their methods to the event OnEnable, and unsubscribe them OnDisable (this is similarly does as with delegates; the += operator subscribes a method to an event, and the -= operator removes the method). It is a good rule of thumb that every time you subscribe a method to an event, you should create a corresponding unsubscribe for it as well. Failing to do this properly can lead to memory leaks and other various errors.

They then describe why this system is effect for dealing with action in your game. The event manager only needs to worry about the event itself and the triggers for the event. It does not need to know about the Teleport of TurnColor script, and these two scripts didn’t need to know about each other either. This helps create a flexible broadcast system.

They then describe the difference between using a public delegate and the event they created. They state that you could acheive the same effect this way, since events are just specialized delegates. The reason to use an event here is that they have inherent security. Events ONLY allow other classes to subscribe and unsubscribe. If a delegate was used, other classes could invoke it or overwrite it.

The take away: if you want to create a dynamic method system that involves more than one class, use event variables instead of delegate variables.

Recap – Week of December 30 to January 6

January 6, 2019

Recap – Week of December 30 to January 6

Terminology from Tactics Tutorials

Physics Constraints

Write Up on Physics Constraints by Hubert Eichner

A nice description of equality constraints, impulse and force based constraints, and other physics constraints used in games.

Priority Queue

Youtube – Priority Queue Introduction

Quick video by WilliamFiset on concept of Priority Queues and Heaps.

Heaps

Youtube – Heap Explanation

Quick video on concept of data structure of heaps, which was a follow up to the priority queue information above.

Subscriber Pattern (Observer Pattern?)

Wikipedia – Observer Pattern

Searching for subscriber pattern resulted in a lot of information on observer patterns, which may be another term for the same thing described in the tutorials. This will require further investigation.

Dictionary

C# Corner – Using Dictionary in C#

Nice, simple write up on basic functionalities of the dictionary type in C#. “A dictionary type represents a collection of keys and values pair of data.”

Youtube – Create a Dictionary Using Collections in C#

This is a basic video tutorial for setting up dictionaries and using them in C#.

Stacks

Tutorials Teacher – Stacks

Tutorial on setting up stacks in C# and some of their functionalities.

Microsoft Documentation – Stacks

This is the Microsoft documentation on everything about the stack class in C# with examples.

Queues

Microsoft Documentation – Queues

This is the Microsoft documentation on everything about the Queue class in C# with examples.

Youtube – How to Work with C# Queues

Simple tutorial initially from Lynda.com about using queues.

Learning Tactics Movement (Cont.) – BFS and Collections

December 22, 2018

Tactics Movement (Cont.) – Programming Collections

Breadth First Search (BFS) and Using Programming Collections

Unity Tutorial – Tactics Movement – Part 3

By: Game Programming Academy

This section begins to finally create the breadth first search algorithm for creating list of available selectable tile options. This section relies heavily on collections type elements in C# programming which I will need to delve into more.

Notes

Look into breadth first search, stacks, queues, and lists.

Stacks: Used to add things to a collection in a certain order and use/apply them in reverse order. Stack uses command “push”.

Queues: Use “enqueue” to add to queue and “dequeue” to remove/pull from the queue.

halfHeight was a variable used to find the center point of the game object in conjunction with the “bounds” and “extents” values of the collider. This is used when positioning the unit on a tile to make sure it is on/above the tile.

Lessons Learned

Had an issue where the mouse clicking functionality wasn’t working. It turned out that the main camera just was not tagged “maincamera”. Make sure to check camera labeling and that it matches what you call out in code when dealing with functions that deal with screen space and the camera.