Unity Composition and Inheritance

July 29, 2019

Unity Composition

Composition vs Inheritance

Youtube – Unity Architecture – Composition or Inheritance?

By: Unity3d College

I was looking to use inheritance with an overall parent abstract class to create a few simple scripts, but was having some trouble getting it setup properly. When looking into how to approach this better, I came across the concept of “Composition vs Inheritance”. This is the first time I heard the word composition, but it appeared to be the idea in Unity of creating a bunch of small scripts that perform specific types of functions that can be placed on objects in a varied structure style to create the proper type of object you want.

I thought this was a neat concept that made a lot of sense in Unity, so I ended up using this idea to approach the issue I was working on. This got me into using RequireComponent(typeof) in Unity, which I’d seen before but never really used. This seemed to be a nice feature to keep track of with a composition style approach since there will probably be a lot of cases where certain components will need others to be there, and this is just a good practice to make sure you don’t have any issues when setting up your structured object.

Updating Waypoint System in Unity

July 19, 2019

Updating Waypoint System

Starting with a base waypoint system I created with the Brackeys tower defense tutorial, I wanted to update it so that the overall path could be altered at run time. Basically, I didn’t want objects traveling along the waypoints to travel the full length everytime. I needed them to sometimes travel part way, sometimes more/less, sometimes the full way.

I decided I would have the main script holding the general waypoint information to hold the value for where objects should stop traveling. This way all objects could reference this for how far they should travel, and I could have anything else just change this single value to update where everything is going. This was as simple as adding an int value called currentEnd to this main script, Waypoints. Then I added the methods GetCurrentEnd (to return currentEnd) and SetCurrentEnd (to change the currentEnd value).

Next was updating the Waypoint_Movement script, which is attached to the objects moving along the waypoints to tell them how/where to move along the waypoints. They were originally moving from waypoint to waypoint until they reached the end of the Waypoints array (Waypoints.points.length – 1, the length of the waypoints array minus 1). This causes them to travel until they hit the end of the array. This was simply changed to check for [Waypoints.GetCurrentEnd() – 1] so they would only move to a waypoint determined by the currentEnd value at the time.

Finally, other scripts were able to add in the SetCurrentEnd() method call from Waypoints to their current functionality to have it basically update the length of the waypoint path further objects would travel.

Creating a First Person Camera Controller in Unity

July 3, 2019

Creating Basic FPS Camera Controller

FPS Controller in Unity

Youtube – How to construct a simple First Person Controller with Camera Mouse Look in Unity 5

By: Holistic3d

This first tutorial is a good example for setting up the most basic type of first person camera in Unity. Since the project I was using didn’t need a character at all and I was just attaching this directly to the camera, I needed to make some slight modifications to have it setup properly. This is because I didn’t have a parent object to apply the second type of rotation to. This just required me to set both rotations in both directions at the same time (since setting one and then the other to the exact same object had the second rotation constantly overriding the first).

This camera had a slight issue though where it moved relative to wherever the mouse starts on the screen. While I was just creating this camera controller for debugging purposes for an AR project, this would be an issue to investigate in the future if you actually wanted to use the controller for a game. Just implementing something simple using the mouse’s initial position relative to screen space somehow.

Tower Defense Tutorial Fixing Scene Manager

Tower Defense Tutorial Fixing Scene Manager

June 19, 2019

Tower Defense Tutorial Project

Fixing Problems with the Scene Manager

To help get back into the groove of working on my tower defense project, I went over some scripts that I thought might help fix problems and listed out how they reference each other. (Lower placed scripts reference the higher ones)

Script Reference List

  • PlayerStats
    • LevelPlayerStats
  • WaveSpawner
    • WaveInformation
    • LevelManager

Then I got working on the problems with the scene manager and the method call timings between the different scenes that were giving me errors. There are a lot of issues when references trying to be called before variables are properly set in different scenes, and this offset is leading to a lot of errors where the checks are checking against default values like 0 and null as opposed to their properly set values. So once again, I made a list of problems as I encountered then and possible fixes I tried, including the ones that finally worked and stuck for now.

SCENE PROBLEMS

Problem

Menu buttons do not work

  • Going back to the level select menu screen is not working on either button, so Menu() method must be incorrect
  • The for loop to deactivate level buttons the player should not have reached yet was given the wrong value to start with when reactivating the scene
    • it was setting a value to the active scene’s index and adding that to the for loop check for the level select button array
    • this value was initializing at 0 the first time through for some reason (another scene timing error), but was then being set to 4 when returning (which I believe is the level scene’s index, so this is another scene timing issue, but being properly set to 3 [the index of the level selection scene] would have been bad as well)
Solutions
  • Solution: Just removed the addition of the current active scene build index all together; I think this was added at some point to process the correct level build indices, but that is no longer needed.



Problem

Retry for a level does not work

  • Clicking retry does unload and reload the current level scenes, but it is done so improperly and the timer does not count do to start the first wave ever
  • Just ever unloading a level scene and trying to load it again has the same problems
    • This indicates something is not being properly reset the second (or more) time the scene is loaded
    • Look to individual Level scene and Base scene (created for all levels), especially in Start type methods
    • EnemiesAlive and WaveIndex are not resetting to 0 when scene is unloaded
      • EnemiesAlive specifically is one of the checks to see if a wave should be spawned (spawns a wave when the value is at 0 to make sure the previous wave was defeated)
Solutions
  • Potential Solution: reset these values to 0 when level scenes are loaded
    • tried this by creating a ResetWaveSpawner method in the WaveSpawner itself, then having something reference this on Start with something that is created on Level load
    • started method in Start method of LevelManager script
      • this actually worked for going back to the menu and then trying the level again, but retry still did not work properly
      • I figured this meant the scenes might be loaded/unloaded differently, so I checked my sceneManagerLite and sure enough, the level selection from the menu needed to load both the Base and Level scene, but retry was JUST unloading/reloading the Leve scene, not the Base scene, which is where the LevelManager is located that is resetting the wave spawner on Start
  • Potential Solution: just have the reset called in the Start method of something in the Level scene itself
    • This did allow the level to start properly when returning to the menu and coming back, or with the simple retry. However, there were still some other problems. Now if you beat a level, every time you returned the game won screen would come up and the game would still play in the background. Leaving the level during play and coming back (by menu or retry) would also change the “Rounds Survived” counter at the end, indicating something with the wave counters was not resetting properly.



Problem

Beating Level Once Beats it Forever

  • After beating level, game won screen comes up immediately when going back to the level
  • Back to our game winning bool checks, appears that the WavesFinished bool is not properly reset when returning to a level. This should be false every time the player starts the level, and get set to true when they win. This is happening correctly, but it is never reset to false.
Solutions
  • Possible Solution: reset the WavesFinished bool in WaveSpawner with proper scene timing
    • Actually just added this to the newly created ResetWaveSpawner method I created to deal with the previous resetting issues and this fixed it



Problem

Wave Spawning Coroutine is Off

  • Resetting a level during the spawning of a wave has the rest of the wave spawn immediately (at the beginning of the newly reset level) as well as spawning the second wave (skips the spawn of the first wave all together)
  • This indicates the coroutine spawning the wave might need manually jumped out of on reset and that the wave index is being messed up by their being enemies remaining

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.

Objects Follow Player in Formation

May 16, 2019

Follow Player Script for Unity

Follow with Formation and Noise

Vimeo – Demonstration of the FollowFormation Scripts with Noise Features

By: Me

This clip just shows off the different aspects and functionalities for my FollowFormation scripts so far.

I was working on a system in Unity for a class project that would allow a player to collect objects around the map by running into them, and then they would follow the player around in some sort of formation. This ended up working better by splitting the concept up into two classes: Leader (on the player object) and Follow (on the following objects).

Leader script

Since we wanted to control the general formation of these objects as well, we’ll start with the Leader script. To make a simple and easily modifiable system, we decided on making a system based on a bunch of transforms childed to the player that would serve as the formation locations. The Leader script basically just grabs all of the children objects and holds them in an array. This is the formationPositions array. It then has a public static method that gives one of these gameObjects and then increments a counter so the next time it is called it returns the next one. This leads into the Follow script.

Follow Script

The Follow script is placed on the objects that will follow the player when collected. The first action is having them be collected in the first place. This is done with a simple collision that starts the following (and turns off the collider so they don’t interact with anything, including the player again). To help with the overall idea of being in formation, the Follow object actually grabs that next gameObject in the formationPositions array to follow around. This is how each object actually gets a different spot in the formation to follow around. With this setup, we just needed to determine how we wanted them to follow.

Various Follow Methods

First, I tried using a combination of LookAt and adding a velocity in the transform.forward direction. This was solid for giving them a bit of an organic movement feel, but it was not very controlled. If the speed was very different from that of the player, their movements felt awkward and they would also tend to clump up. This could be an interesting solution route, but it would take a lot more work to function properly.

Next, we looked at simply setting the transform.position to the follow object. This wasn’t great as it looked very mechanical, especially immediately upon collecting the object. It would just teleport behind the player.

Finally, we settled on using a Lerp function along with the transform.position. With use of an additional speed variable, this gave us a nice, smooth motion that was easy to modify to give various feels.

FormationNoise

After settling on the foundational movement for the following objects, we wanted to look into adding some noise to their movements to make them feel a bit more lifelike. Since I knew there were going to be a few different options of noise I’d like to switch between to see which ones felt better/worse with different parameters, I looked into setting up an enumerator with a switch case statement to easily switch between these different options. I simply created an enum called Motion that held a value for each of the different types of noise I made, and had a switch case check the Motion motion to determine which noise that specific object would use. This ended up being extra nice as I could also have different objects testing different types all at once.

It should also be noted that in order to keep things simple, I added the FormationNoise script directly to the formation position gameObjects that were childed to the player. Moving these simple transform objects would in turn move the following object following it as it is specifically given this gameObject transform to follow.

Finally, since everything was dealing with keeping these objects in the general area designated for their spot in a formation, the initialLocation is recorded on Start so we know its initial localPosition. This helped move the objects around this point, as opposed to continually adding or something and having it fly out of position.

Noise Methods

The first noise we tried was a simple random range applied to the entire position vector of this formation position object. I created a variable for the max and min of the random range to randomly sift through, and every frame a value in this range would be added to the initialLocation. This actually ended up being pretty nice for creating a “buzzing” or “vibrating” effect, which was nice since these would eventually be applied to bee characters for the ‘ project, but other than that it was not very interesting motion.

Since that method seemed a bit too hectic, I wanted to test just adding some noise to a single dimension. I chose the x-axis to randomize along since that seemed like it would give the most interesting results from my camera top view. This did seem a bit more controlled, but still mostly just had a “buzzing” feel to it.

Finally, I thought about what general motion I would like along with the noise and I thought a nice overall controlled swaying and/or bobbing would be nice to have with the noise. This method got a bit more involved. I created a sway variable, which would determine the amplitude they would drift on a given axis (for initial testing, I just did the x-axis). I also created a swaySpeed to determine just how fast they moved between the max and min sway locations.

Since I liked the “buzzing” feel of random moving the point around a small range, I kept that for the y-axis and z-axis. I just had the sway controlling the x-axis movement. This had the object buzz around a bit as it moved back and forth relative to its given initial formation position. This all led to a nice movement that was still very controlled, but felt a lot more alive.

POTENTIAL IMPROVEMENTS

The movement of the objects when they are following a significantly fast player still looks pretty direct and parented. It appears that if their overall speed is much greater than the movements/speed of their internal noise methods, the noise gets a bit lost or drowned out. This is something I will just have to player with more when dealing with the relative speed of the following objects and the player.

Possibly control more axes of noise a bit more. Adding a bobbing effect by swaying in the y-axis would give a nice effect. If we control too many axes, we’ll have to recheck if it’s still a nice effect or if we’ll need to add more actual noise to the movements again to keep them from feeling too robotic.

Currently the setup of the Leader’s formationPositions array only makes an array the size of how many children the player object has at startup. This makes the system a bit rigid, or require having a bunch of unneccessary children objects for a while with possible errors for large numbers of followers exceeding the array count. A more variable system might use a list instead of an array, or just a large array with some method that creates gameObjects as followers are gained to add to that array.

Dynamic Batching/GPU Instancing in Unity

May 7, 2019

Dynamic Batching/GPU Instancing

Following Tutorial

Youtube – [Unity] GPU Instancing Tutorial

By: Blendcraft Creations

In Unity, the benefits of GPU instancing may not be imediately noticeable by the FPS alone in the editor. This first tutorial shows that the FPS is more properly represented in an actual build of the project. Even though this is an older Unity version, that is still good to note to test all the way through to see if you are getting the expected results.

Following this tutorial appeared to work as intended, but it did have a weird issue where I couldn’t create lower numbers of instances of objects. Upon inspecting the script, I determined that any number below 1000 most likely would not be rendered out based on the for loop creating the batches at start. The following code snippet is where the issue was occurring:

private void Start()
{
int batchIndexNum = 0;
List currBatch = new List();

for (int i = 0; i < instances; i++)
{
AddObj(currBatch, i);
batchIndexNum++;
if(batchIndexNum >= 1000)
{
batches.Add(currBatch);
currBatch = BuildNewBatch();
batchIndexNum = 0;
}
}
}

I amended this with a quick fix using a small snippet after the entire for loop as follows:

if(batchIndexNum != 0)
{
batches.Add(currBatch);
batchIndexNum = 0;
}

This allowed me to now render numbers of instances less than 1000, and theoretically allowed me to render instances of any amount now, where initially it would only render multiples of 1000.

I would need to do further analysis to really understand the processing benefits of this, but it is a nice start to at least see that it is working and creating many instances of an object for me. I was safely able to create a few thousand instances of simple objects and run the game in the editor for what it’s worth. I also added a very basic 3D player controller that mostly moved the camera around to get a better idea of how everything was running with all of these objects created.

Look Into – Coding
  • Graphics.DrawMeshInstanced()
  • Operator: =>

Learning Scriptable Objects in Unity

May 6, 2019

Scriptable Objects in Unity

Basic Tutorials

Youtube – Unity3D – Using ScriptableObject for Data architecture / sharing

By: Unity3d College

Youtube – Introduction to Scriptable Objects – Unity 2018 Tutorial

By: Chris’ Tutorials

Youtube – How To Improve Your Game With Scriptable Objects – Unity

By: Dapper Dino – Coding Tutorials

I’m just saving some decent looking tutorials from starting with scriptable objects in Unity. These are something I still haven’t really gotten to in Unity, and I especially want to get a handle on them since they are apparently a useful tool in passing information between scenes using the new scene management approaches in Unity.

Pokemon in Unity – Tutorials

April 28, 2019

Making Pokemon in Unity Tutorials

Youtube – Lets Make… Pokemon in Unity! – Episode 1 – Basic Setup World/Character

By: BrainStorm Games

Youtube – Unity Lets Clone a Game [ Pokemon ] – Part 1

By: JesseEtzler

Going off of my recent trend, I’ve just been looking to grab tutorials to make games I loved (or still love) playing as a way to learn more about coding different systems in Unity with C#. I believe the Pokemon games will help get me into some scripts that are very repeatable on a large scale (such as a script that creates a pokemon and its stats), which is something I haven’t gotten into a lot.

Being an RPG game with random encounters, it may also help me work in a system that very consistently moves between two major scene types with the overworld scenes and the battle scenes. These scenes will also give the player very significantly different actions while still carrying information between the two types of scenes.