UnityLearn – Beginner Programming – Tips & Considerations – Pt. 05

October 29, 2019

Beginner Programming: Unity Game Dev Courses

Beginner Programming: Unity Game Dev Courses

Unity Learn Course – Beginner Programming

Tips & Considerations

Unity’s Order of Events

Unity’s Order of Events:
Awake : OnEnable : Start : Update : OnDisable : OnDestroy

  • Awake: first function called when object is instantiated; true whether added to scene in editor or instantiated in code
  • OnEnable: event; fired when enabled gameObject is instantiated or when a disabled object is enabled
  • Start: after Awake, and OnEnable, but before the 1st frame update
  • Update: happens every frame after initialization methods
    • FixedUpdate: frame-independent and occurs before physics calculations are performed
    • LateUpdate: called once per frame after update method has completed execution
  • OnDisable: event; fires when object is disabled, or before it is destroyed
  • OnDestroy: execute when object is destroyed in code, or when scene containing it is unloaded

Reference Caching: creating a field for a reference and getting that reference once during initialization to use whenever that object is needed

This information is very useful to understand when you start referencing a lot of objects throughout your code and have a lot of pieces working together. This will help with avoiding errors, and debugging when those types of issues do come up. This is something I ran into a lot when working on my scene manager project as getting references was a bit of a pain and the timing was very crucial.

Using Attributes

Attributes (C#): powerful method of associating metadata, or declarative information, with code
Unity provides number of attributes to avoid mistakes and enhance functionality of inspector.

Some common attributes used in Unity include:

  • SerializeField: makes a field accessible to the inspector
  • Range
  • Header
  • Space
  • RequireComponent

Public fields are inherently accessible by the inspector, but many other access modifiers hide the field from the inspector (like private). To get around this, you add the SerializeField attribute.

The RequireComponent attribute takes in a type and automatically adds that component type to the same gameObject whenever this object is placed. It also ensures that the other component cannot be removed while this component exists on the gameObject.

UnityLearn – Beginner Programming – Delegates, Events, and Actions – Pt. 04

October 25, 2019

Beginner Programming: Unity Game Dev Courses

Beginner Programming: Unity Game Dev Courses

Unity Learn Course – Beginner Programming

Delegates, Events, and Actions

Delegates

Delegate: in C#, a type designed to hold a reference to a method in a delegate object

  • Delgates are created using the “delegate” keyword.
  • They are defined by their signature, meaning their return type.
  • Finally they have parameters which they take in, similar to methods.

Using a delegate allowed us to parameterize a method. Using the delegate as a parameter for a method also allows us to use any method which matches that delegate’s signature to satisfy the parameter.

These are some snippets from two scripts, GameSceneController and EnemyController, that show some basics of utilizing delegates:

– In GameSceneController script
public delegate void TextOutputHandler(string text);

public void OutputText (string output)
{
Debug.LogFormat(“{0} output by GameSceneController”, output);
}

– In EnemyController script
void Update()
{
MoveEnemy(gameSceneController.OutputText);
}

private void MoveEnemy(TextOutputHandler outputHandler)
{
transform.Translate(Vector2.down * Time.deltaTime, Space.World);

float bottom = transform.position.y – halfHeight;

if(bottom <= -gameSceneController.screenBounds.y)
{
outputHandler(“Enemy at bottom”);
gameSceneController.KillObject(this);
}
}

For example, in our case we created a public void delegate with a string parameter called TextOutputHandler. Then another one of our methods, MoveEnemy, took a TextOutputHandler as a parameter, named outputHandler. Any method matching the signature of the delegate (in this case, public void with input parameter string) can satisfy the input parameter for the MoveEnemy method. As can be seen in the example, whatever method is passed in will be given the string “Enemy at bottom”.

A delegate used this way is commonly known as a “Callback”.

Events

C# Events: enable a class or object to notify other classes or objects when something of interest occurs.
Publisher: class that sends the event
Subscriber: class that receives/handles the event

Things like Unity’s UI elements use events inherently. For example, the Button script uses events to tell scripts when to activate when a button is clicked. This is different from a basic way of doing inputs which checks every frame if a button is being pressed (which is called “polling”). This is also why creating UI elements in Unity automatically creates an EventSystem object for you.

In C#, events are declared using the “event” keyword, and all events have an underlying delegate type.
C# events are multicast delegates.
Multicast delegate: delegate that can reference multiple methods

To help with my understanding, I tried testing the setup without having an EnemyController parameter to see why it was needed. I discovered it was necessary to pass along the reference so the small event system knew which object to destroy when calling the EnemyAtBottom method. Using Destroy(this.gameObject) or Destroy(gameObject) both just destroyed the SceneController as opposed to the individual enemies. This also helped me understand that adding a method to an event does not pass the method over as an equivalent, it simply means that when that event is called, that any methods assigned to it are also called in their current location in a class. So even though the event was being called in the EnemyController script, the method I added to it was still called within the GameSceneController script, which makes sense.

Example:

In EnemyController script


public delegate void EnemyEscapedHandler(EnemyController enemy);

public class EnemyController : Shape, IKillable
{
public event EnemyEscapedHandler EnemyEscaped;

void Update()
{
MoveEnemy();
}

private void MoveEnemy()
{
transform.Translate(Vector2.down * Time.deltaTime, Space.World);

float bottom = transform.position.y – halfHeight;

if(bottom <= -gameSceneController.screenBounds.y)
{
if(EnemyEscaped != null)
{
EnemyEscaped(this);
}
// Can be simplified to:
// EnemyEscaped?.Invoke(this);
}
}
}

In GameSceneController script:


public class GameSceneController : MonoBehaviour
{
private IEnumerator SpawnEnemies()
{
WaitForSeconds wait = new WaitForSeconds(2);

while (true)
{
float horizontalPosition = Random.Range(-screenBounds.x, screenBounds.x);
Vector2 spawnPosition = new Vector2(horizontalPosition, screenBounds.y);

EnemyController enemy = Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);

enemy.EnemyEscaped += EnemyAtBottom;

yield return wait;
}
}

private void EnemyAtBottom(EnemyController enemy)
{
Destroy(enemy.gameObject);
Debug.Log(“Enemy escaped”);
}
}

I’ve simplified the scripts down to just the parts dealing with the events to make it easier to follow. As I understand it, we create the delegate: public delegate void EnemyEscapedHandler(EnemyController enemy) in the EnemyController script (but outside of the EnemyController class). Within the EnemyController class, we create an event of the type EnemyEscapedHandler, so this event can take on methods with the same signature as EnemyEscapedHandler. Within the MoveEnemy method, we invoke the EnemyEscaped event and satisfy its parameters by passing in this, which is the unique instance of the EnemyController script (after checking that there is a method assigned to this event).

Then in the GameSceneController script, we see that when we instantiate an enemy, we keep a reference to its EnemyController script. This is to assign the EnemyAtBottom method to each one’s EnemyEscaped event. Now anytime EnemyEscaped is called in the EnemyController script, it will then call the EnemyAtBottom script here, passing whatever parameter it (EnemyEscaped) has to the parameter for EnemyAtBottom. In this case, passing this in EnemyEscaped ensures that EnemyAtBottom knows which enemy to destroy.

Actions

Actions (C#): types in the System namespace that allow you to encapsulate methods without explicitly defining a delegate
In fact, they are delegates
Actions can be generic

An Action is just an event delegate that does not need another delegate to be created first to be used as a reference. The Action itself determines what parameters are necessary for the passed methods.

Thesis Project – Concepts for System to Control Script Timings

October 24, 2019

Working with the HFFWS

System for Properly Timing Running of Scripts

Discovering the Timing Issues with the HFFWS Tools

While working with the Rope script in the Human API, I was again encountering timing issues when trying to accomplish tasks through script. I was having trouble instantiating and connecting rigid bodies to the ends of the rope in script. I ran several tests to confirm the timing issues I was having again.

Test #1
  • 2 Rigid Body objects exist in scene
  • Script has 2 gameObject references for those objects
  • Script sets startBody and endBody references to those objects at Start

This did not work. The references could be seen as being properly assigned in the Rope script in the editor, but that connection was being made too late and having no affect on the objects.

Test #2
  • 2 Rigid Body objects exist in scene
  • Script has 2 gameObject references for those objects
  • Script sets startBody and endBody references to those objects at Awake

This did have the intended result of connecting the rigid body objects to the rope.

Test #3
  • All done in Awake
  • 2 Rigid Body objects instantiated into scene
  • Script sets startBody and endBody references to those objects at Awake

This did work once, although I had some issues repeating it afterward. The objects were prefabs which were instantiated in Awake. GameObject references were created for these, and used for the values of the Rope script startBody and endBody, all done in Awake as well.

Test #4
  • Start or Awake is irrelevant here
  • Object with Rope script starts deactivated
  • 2 Rigid Body objects instantiated into scene
  • Script sets startBody and endBody references to those objects
  • Rope object is then activated

This is the best solution that works, as it can be done in Awake or Start. This leads to a much more controllable environment which is ideal for our system. This will be the foundation for the main systematic approach.

System for Controlling Awake Calls for HFFWS Objects

Deactivating/Activating Objects or Enabling/Disabling Scripts

The combinations of all of these tests, most notably Test #4, showed that some important connections are made during the Awake phase of many HFFWS objects. It is important to note that Test #4 specifically indicates that a lot of the important functionality may be happening in the Awake method of the scripts of the individual objects themselves (which is important to differentiate from some system wide class that is making connections in Awake). This important differntiation leads to this option of simply deactivating objects with HFFWS scripts (or possibly disabling the scripts specifically) to force their Awake methods not to run before my systems are ready for them. I can run my scripts, and then activate the HFFWS objects so their Awake methods run at that point instead.

This concept seems the most promising for safely and consistently controlling the timing of my script elements versus those of the HFFWS objects (since I do not have access to their core scripts). As this is a common issue I have run into with many objects, it makes sense to make a small script to attach to any prefabs I will be instantiating which can just hold references to gameObjects and/or scripts that I will need to have deactivated or disabled initially, and then activate or enable after everything is properly set.

Script Execution Order

This was actually the first idea to get around these timing issues, but it seems less safe so it will most likely only be used as a last resort. The HFFWS package already has a lot of various scripts ordered in the script execution order of Unity, so there is already a precedent set by them for when a lot of things should run relative to each other.

To test that this worked in the first place, I ran a test with everything being set in Awake not working but moving it to the first script in the script execution order actually made it work. This was a similar test with connecting rigid bodies to a Rope script object.

This is not an ideal process to use however as it can easily lead to weird behavior that is very hard to debug and will not scale well in general. Because of these factors, I will mostly be looking to expand upon the other system concept.

UnityLearn – Beginner Programming – Working with Classes – Pt. 03

October 22, 2019

Beginner Programming: Unity Game Dev Courses

Beginner Programming: Unity Game Dev Courses

Unity Learn Course – Beginner Programming

Working with Classes

The Four Pillars of OOP
  • 1. Encapsulation: grouping of data and methods into a cohesive object
  • 2. Abstraction: process of exposing only those features of an object necessary for interactions
  • 3. Inheritance: creating a new class based on and extending another
  • 4. Polymorphism: ability of an object of function to take on a different form

The PlayerController class created for this section of the tutorials dervied from the Shape class, which allowed it to inherit the SetColor method and change the player to yellow. It also extended the class by creating its own method, MovePlayer. I am trying to keep track of this to ensure I keep all the terminology straight.

There was an interesting approach to using WaitForSeconds in the enemy spawning method. Instead of directly using new WaitForSeconds directly in the yield return statement of the coroutine, they actually created a WaitForSeconds variable reference named wait. They then just used wait in the yield return statement in place of all the WaitForSeconds syntax. This is nice to keep in mind as another way to organize coroutines, especially those that use similar values for multiple yield statements.

Inheritance and Polymorphism

Inheritance was demonstrated by creating protected variables within the base class that could be used by all of the derived classes. The examples here were halfHeight and halfWidth, which assumed the values of the bounds.extents of the SpriteRenderer at Start. This was done in the Start method of the base class, so the derived classes simply had to call base.Start() to have those values individually set for all of them inheriting from Shape class.

It is important to note for this to work they made the Start method in the base class a virtual protected method. This allowed the derived classes to override the Start method to add functionality, while also using the base.Start() method still to assume the base class’s Start method functionality. This started to get into polymorphism.

virtual: this keyword can be used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class

IMPORTANT: This can be used in conjunction with the protected access modifier to allow for a base class’s Start method to be useable within the Start method of derived classes. By creating a protected virtual void Start method in the base class, the derived classes can have their own modified Start methods by using a protected override void Start method and calling the base.Start() method from within.

Unity Procedural Landmass Generation by Sebastian Lague

October 21, 2019

Procedural Terrain Generation

Tutorial

Procedural Landmass Generation (E01: Introduction)

Tutorial #1 – Link

By: Sebastian Lague


This is the beginning of a procedural landmass tutorial by Sebastian Lague. This appears to get move involved in setting up noise with more controlled variability along with shading and other interesting tricks. This will compliment a procedural terrain tutorial I followed by Brackeys since this gets much more involved and gives many more designer options.

Unity Card Game Tutorials – Drag and Drop

October 15, 2019

Unity Card Game Tutorials

Drag and Drop

Youtube – Unity Tutorial – Drag & Drop Tutorial #1 [RPGs, Card Games, uGUI]

Tutorial #1 – Link

By: quill18creates


I was interested at looking into how card games are created in Unity as I was interested in possibly making that type of game and also thought it would be something good to look into for my current research on learning how to effectively create my own class systems that utilize interfaces and inheritance well. Cards are a very obvious type of object that will use a similar setup every single time, so they are a nice simple base to focus on creating a nice class that contains everything you should need for all of your cards. Interfaces could then be a good way to give these elements their interactive components (such as dragging them around or sending them to their proper locations during gameplay).

This video is actually the first in a series of three. They mostly cover interactivity in a card game, with a focus on dragging and dropping, with some visual clarity effects (like moving the cards around for you). There is still some coverage on the general “card” class as well.

HFFWS Fixing and Debugging the Pulley Generator

October 14, 2019

Pulley System Generator

Fixing

Notes:

– Deselecting “Fix Start” and “Fix End” on the Rope component allows for the creation of a simple rope that appears to operate normally, but it is not connected to anything
– “Fix Start” and “Fix End” appear necessary to connect the rope to physics objects

TESTING

Issue 1:

Instantiated Rope is a completely broken mess of physics masses jumping around.

Test 1:

Changing objects at ends to TestBox and TestSphere just to simplify the physics objects involved to see if that makes diagnosing the problems easier

Results:

This did result in a more stable rope. It was still not in the correct location, but the rope was no longer just a jumbled bumbling mess of masses.

Issue 2:

Rope is instantiated in a strange position away from most other objects.

– This appears to be because of the ropeStart and ropeEnd positions. The rope is still following their positions, and they are far away.
– The ropeStart and ropeEnd positions however do have the same Y and Z values, suggesting that they are following the logic to some degree, but not as intended.

Test 1:

Change instantiation process so that pulley end objects are instantiated as children of the overall pulley prefab.

– The idea is that this will help with relative positioning
– I am not sure if I can use this method with a prefab that has not been instantiated yet (seems strange using the transform of an object that does not exist yet)

Results:

– This did properly situate the rope end physics objects at the ends of the rope, however the rope was still spawning in a location that was unintended, below everything else.
– The rope also does not appear to actually be bound by the end objects either.

Test 2:

Debug.Log all the positions to see if the positions occurring at run time are matching those in the script.

Results:

– The script dictates that the start physics object is positioned at (-9.5, 0, 0) – (1.0, 0, 0), so (-10.5, 0, 0) relative to its starting position, and the end physics object is the reversse (+9.5 and +1.0). This indicates that there should be 21 units between them. This did happen, but the values are very different looking.
– The start instantiated at position: (-2.5. -14, 35.5)
– The end instantiated at position: (18.5, -14, 35.5)
– This indicates that the parent position they are referencing is: (8.0, -14, 35.5)
– Both RopeStart and RopeEnd child objects’ positions matchup with the weird physics object positions as well, so it’s before them.

SOLVED:

Turns out the overall prefab had the exact transform position (8.0, -14, 35.5) so those values were getting passed into everything as the starting parent transform value

Issue 3:

Rope is not actually connected to the physics objects at the ends.

– This is accomplished by setting the connectedBody reference of the RopeStart and RopeEnd objects to the rigid body components of the start physics object and end phsyics object respectively.
– This is happening as seen in the references at run time, which makes me expect that this connection is still somehow ‘ being made before the instantiation of the full pulley setup.

Test 1:

Run everything in Awake instead of Start

– I thought running everything sooner may help set the connection up earlier.

Results:

– There were no noticeable differences.

NEXT STEPS

Figure out how to actually connect the objects to the ends of the rope.

HFFWS Rope Pulley System Issues and Strange Audio Instantiation

October 9, 2019

HFFWS Thesis Project

Creating Pulley System

Creating Pulley in HFFWS

Working with the Rope Script

The Rope script is the central focus for the pulley system, but the Fixed Joint that goes with the rigid body of the ropeStart and ropeEnd also play a crucial role which makes getting everything to work together nicely a bit of a challenge. I want the setup to be able to take in a prefab for each end of the pulley and instantiate those objects in the proper position, and then become connectedBody for each of these Fixed Joints. Similar to other issues I have had before with instantiating objects, there seems to be a critical timing factor needed on top of the fact that the objects just physically behave very weirdly when created.

I think currently there is some collision issue that is occurring because the rope ends up spawning very far away from where it is intended to spawn and also waves around violently. Meanwhile, the objects that are supposed to be at the rope ends are spawning in the correct position. The demolition ball just falls to the ground while the hinged platform moves back and forth some.

The connectedBody reference on the Fixed Joints is something that needs to be done on initialization to work properly, so I have been trying to instantiate the rope end objects first, then setting the prefab’s Fixed Joint connectedBody’s to these objects’ rigidbody’s, and then instantiating that prefab, but this is clearly leading to some significant errors. I will have to try some other approaches where I change the order of events to see if I can get more desireable results, or just understand where the errors are occurring more accurately.

Weird Audio Issue

Weird Siege(Clone) Issue There was a Siege(Clone) object being instantiated at game start. This had lots of audio files. I tracked this to the Level gameObject which has a SoundManager component. This had a Stored State of Siege which I removed. This stopped Siege from instantiating anymore. I am not sure how this got set in the first place (may happen when loading other scenes or checking the prefab scenes). The SoundLibrary component also has a Siege reference in its path: Path = 6Siege. However this does not appear to be doing anything currently.

UnityLearn – Beginner Programming – Pt. 02

October 8, 2019

Beginner Programming: Unity Game Dev Courses

Beginner Programming: Unity Game Dev Courses

Unity Learn Course – Beginner Programming

Understanding Types

What is a Type

Overview: Types of types, “var” keyword, enumerations, generics
Data Type: data type or simply type is an attribute of data which tells the compiler or interpreter how programmer intends to use the data.

Types of types: Value types and Reference types
  • Value Types: Memory is allocated directly and inline on the stack
  • Examples: int, byte
  • Reference Types: Memory is allocated randomly on the managed heap
  • Examples: Classes, delegates, interfaces
Memory Allocation by Type
  • There are two main memory storage locations we are concerned with, the stack and the heap.
  • Value types and pointers to reference types are located in stack (pointers not directly used in C#)
  • Reference types are located in heap
Stack vs. Heap
  • Stack
    • Allocated when compiled
    • Data are stored sequentially
    • Variable size must be known
    • Not subject to garbage collection
    • Very fast
  • Heap
    • Allocated during runtime
    • Data are stored randomly
    • Variable size can be unknown
    • Subject to garbage collection
    • Slower

The var Keyword and Anonymous Type

The var keyword allows for implicit typing but must be used within method scope. C# can use the value of a var variable it is initialized to to determine what the type should be. This is implicit typing. This also means we cannot declare a var variable without intializing it. Type inference occurs at the compiler level, so it does not effect performance.

Anonymous Type
  • An unnamed container for properties
  • properties are read only
  • no type name available to source code
  • type of each property is inferred

Enumerations

Enumeration: value type that represents a set of related named integral constants; declared using enum keyword
The underlying type of each element of an enum is int. These default to having values of 0, 1, 2, etc. The underlying int values can be set for each element individually however if wanted.
Benefits of Enumerations:

  • value types
  • express and limit available options for a variable’s value
  • named values provide readability
  • leverage Intellisense

Generic Types

Generics allow you to defer type declaration until use.
Benefits of Generics:

  • flexibility
  • code reuse
  • performance
  • type safety

Generics are used with the syntax of , where T is a type parameter. An example is shown below:
private void Evaluate(T suppliedValue)
{
Debug.LogFormat(“the Type of {0} is {1}”, suppliedValue, typeof(T));
}

Generics can be used in similar scenarios where overloaded methods would make sense, but would clutter things because there are many different types you would like a similar method to be able to use. Since you are also using a single method for vaarious types, it will also be performing the same actions on those types, so overloaded methods may be better if you want different actions for different types.

Working with Groups of Types

Module Introduction and Setup

Overview: arrays, generic lists, dictionaries, Queues & Stacks

Arrays

There was nothing new here.

Generic Lists

Lists are part of the System.Collections.Generic namespace. Lists are a generic class that use the type T type parameter.

Dictionaries

Dictionary: in C#, it is a collection type defined in System.Collections.Generic namespace that can store any data types in the form of keys and values.
Similar to other type parameters, they are declared between angle brackets for dictionaries. In arrays and lists, the elements are referenced by an integer index. A dictionary allows you to use a different type of index to reference your collection elements.

Queues and Stacks

Queues and stacks are used for more transient data, as opposed to arrays, lists, and dictionaries which are for more persistent data. The main difference between queues and stacks is the order in which data is removed. Queue is FIFO (First in, First out), where stack is LIFO (Last in, First out).

Coroutines

Introducing Coroutines

Coroutine: In Unity, a function declared with a return type of IEnumerator that allows execution to be suspended and resumed using the yield keyword.
Coroutines allow execution to be suspended and resumed using the “yield” keyword. The execution will run until it hits this keyword, then suspend this operation based on the value returned. This lets Unity continue any other operations going on while retaining its place in the coroutine. The value returned determines how long execution will be suspended. For example, returning null simply suspends execution until the beginning of the next frame. This ability to suspend and resume coroutines is what makes them so useful. The fact that coroutines must be of the return type IEnumerator dictates what values it can return, which means it dictates what values can be used to determine the time its routine execution can be suspended.

Delaying Execution

Coroutine Wait Types:

  • WaitForSeconds(): waits using scaled time
  • WaitUntil(): suspends execution until supplied delgate evaluates to true
  • WaitWhile(): suspends execution until supplied delgate evaluates to false
  • WaitForEndOfFrame(): waits until the end of the current frame
  • WaitForFixedUpdate(): waits until the next fixed frame update
  • WaitForSecondsRealtime(): waits for some time, but uses unscaled time
Time.timeScale

This can be used for a slow motion effect, or even pausing the game in Unity. Setting this to 0 is a common technique for pausing a game. Since WaitForSeconds uses scaled time, this will also stop any coroutines using that as the return type. However, if the coroutine uses WaitForSecondsRealtime(), which uses unscaled time, it will continue to run even at a Time.timeScale of 0. This difference can be useful if you want certain UI elements to perform some action for example while your main game is paused.

IMPORTANT: Yield statement does not return out of the function, it simply suspends execution. When it resumes, it picks up right where it left off.

Running in Parallel

Coroutines can be used for parallel processing. Coroutines allow processes to be split across multiple frames. This can also be used to let them be run in parallel with other game logic to minimize impact on frame rate.

Module Summary

Stopping a Coroutine:

  • StopAllCoroutines(): stops all coroutines running on a MonoBehaviour
  • StopCoroutine(): stops a specific coroutine running on a MonoBehaviour

The way coroutines are stopped depends on how they were started. If started with a string, they must be ended with a string. If started with a reference to the routine, it must be stopped using that reference.

Coroutine Caveats

  • can result in unexpected behavior (it is very easy to accidentally run a coroutine more than once)
  • can make debugging more difficult, since one or more coroutines can be running at a time along with update
  • can be complex and difficult to manage

How to Spawn Objects anywhere in Unity3D from Unity3D College

October 7, 2019

Spawn Objects in Unity

Basics and Addressables

How to Spawn Objects anywhere in Unity3D (and a bit of addressables)

Youtube – Link

By: Unity3d College


I wanted to note this as a possible useful source since my thesis work will involve spawning a lot of objects, and in varied and rather precise positions. With how important of a focus it will be, I figure more sources on the generals of spawning objects would be good to know to give me as many tools to use as possible.