Friday, May 5, 2017

8 Bit History - Episode 1 - Bomberman 64 - Who Is Regulus ? - Where is Regulus? (SCRIPT)

By Jose R Cordero Ladner (Joey 6'1'')

Videos:https://www.youtube.com/watch?v=gqaQxTiAXK0&t=57s

While Bomberman 64 isn't the first game in the Bomerman series, it was loved by fans for a variety of reasons. From the great adventure mode to the high quality single-player mode however, the multiplayer for the game wasn't as highly rated by gamers or critics.

The game is the first 3D entry to the Bomberman series and is focused around platforming which is different to the original game. The original game was focused around arena's filled with enemies and other environmental dangers.

Over 40 developers from Hudson Soft [1] worked on bringing the game to life and it was finally released in 1997 for the Nintendo 64. However, the game was also released in 2017 for the Wii U Virtual Console allowing players to revist it. While Hudson Soft developed the game, Nintendo published it in North America and Europe.

One of the big baddies in the game is Regulus, one of the Masked Trio who serves under Altair and is his right-hand man. Unlike the other villians in the game, Regulus becomes an ally to Bomberman and even supports him in the final fight against Siruis. During the final fight, the player must also ensure that Regulus survives the fight while also defeating Siruis.

This isn't the end of Regulus however as he's also featured in Bomberman 64: The Second Attack! where he is called “Bulzeeb” instead throughout most of the game. Towards the end of the game however, he rejects the name and demands to be called “Regulus” once again.

There was some suggestion from fans that Regulus could be in the Super Bomberman R game which was released in March. Fan theories stated that the “R” could stand for “Reunion” [2]. However, this turned out to be incorrect and there was no Regulus.

There have been no hints from Hudson Soft or Nintendo about a possible Bomberman 64 release for the Nintendo Switch eStore. Hopefully the developer and publisher will release a statement in the future confirming that this classic game is getting another lease of life.

Alternative Image

Source: http://t13.deviantart.net/JD9ZAYQ-lwTW5REFVaKhq-XotTY=/fit-in/700x350/filters:fixed_height(100,100):origin()/pre06/dadf/th/pre/i/2012/302/7/1/regulus_by_picano-d5jdvx6.png 





Developers [1] http://bomberman.wikia.com/wiki/Bomberman_64/Staff 
Fan suggestion [2] https://www.gamefaqs.com/boards/204231-super-bomberman-r/74866281 

Monday, April 3, 2017

#11 Download Megaman 7: Bass Edition - Here!!!

Download Megaman 7 : Bass Edition by Falchion 22
RIGHT HERE

https://www.mediafire.com/?aiuecdzcur9evwl

let us know, what do you want to change, piece!

Monday, March 6, 2017

#10 Frames per second


Frames Per Second

 
Measuring Performance
  • Use physics to create an ever-growing atomic nucleus.
  • Use the profiler to investigate performance.
  • Measure and display the frame rate.
  • Prevent the creation of temporary strings.
  • Stabilize the frame rate by averaging multiple frames.
  • Colorize the frame rate display.

In this tutorial we'll create a simple test scene and then measure its performance. We'll first examine the profiler, then we'll create our own frame rate counter.
This tutorial requires a basic understanding of scripting in Unity. It has been made for Unity 5.0.1 and up. If you're new, have a look at Constructing a Fractal first.

Smash together spheres until your frame rate tanks.

Building an Atomic Nucleus

We need a test scene. One that ideally covers both high and low performance situations. I suggest we create an atomic nucleus by fusing more and more nucleons together. As the nucleus gets bigger, performance will worsen.
The nucleons will be simple spheres that will be attracted to the center of the scene, where they will bunch up and form a ball. This is of course not a correct representation of an atom, but that's not the point.
We can model a nucleon with a default sphere and a custom Nucleon component. This component makes sure that a rigidbody is attached to its object and then simply pulls it towards the origin. The strength of the pull is determined by a configurable attraction force and the distance from the center.
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Nucleon : MonoBehaviour {

 public float attractionForce;

 Rigidbody body;

 void Awake () {
  body = GetComponent<Rigidbody>();
 }
 
 void FixedUpdate () {
  body.AddForce(transform.localPosition * -attractionForce);
 }
}
Create two nucleon prefabs using spheres, one for protons and another for neutrons. Give each a different material so they look distinct. We could suffice with only one nucleon type, but that's boring to look at.
proton neutron
Nucleon prefabs.
To spawn these nucleons we need to create another component, NucleonSpawner. It needs to know the time interval between spawns, how far away from the center to spawn, and what to spawn.
using UnityEngine;

public class NucleonSpawner : MonoBehaviour {

 public float timeBetweenSpawns;

 public float spawnDistance;

 public Nucleon[] nucleonPrefabs;
}
Create an empty game object, attach a NucleonSpawner component, and configure it as you like.
Nucleon spawner.
To spawn at regular intervals, we need to keep track of the time since the last spawn. We can do this with a simple FixedUpdate method.
 float timeSinceLastSpawn;

 void FixedUpdate () {
  timeSinceLastSpawn += Time.deltaTime;
  if (timeSinceLastSpawn >= timeBetweenSpawns) {
   timeSinceLastSpawn -= timeBetweenSpawns;
   SpawnNucleon();
  }
 }
The actual spawning consists of three steps. Pick a random prefab, instantiate it, and give it a random position at the desired distance.
 void SpawnNucleon () {
  Nucleon prefab = nucleonPrefabs[Random.Range(0, nucleonPrefabs.Length)];
  Nucleon spawn = Instantiate<Nucleon>(prefab);
  spawn.transform.localPosition = Random.onUnitSphere * spawnDistance;
 }
nucleus


Building a nucleus through bombardment.
Playing this scene should result in spheres shooting towards the center. They will overshoot for a while, until they collide with each other so much that a ball is formed. This ball will keep growing, physics computations will become more complex, and at some point you will notice a drop in frame rate.
If it takes too long for you to see performance worsen, you can increase the spawn rate. Speeding up time by increasing the time scale works as well. You can find it via Edit / Project Settings / Time. You can also decrease the Fixed Timestep, which will result in more physics calculations per second.
Unity time settings.
unitypackage

Using the Profiler

Now that we have a scene that will eventually bring down the frame rate of any machine, it is time to measure the actual performance. The quickest thing you can do is enable the statistics overlay of the game view.
Game view statistics overlay.
However, the frame rate shown there isn't accurate at all, it's more like a rough guess. We can do better by opening Unity's profiler, via Window / Profiler. The profiler gives us a lot of useful information, especially the CPU usage and memory data.
The profiler, showing lots of vsync time.
If vsync is enabled, it will likely dominate the CPU graph at the start. To get a better idea of how much CPU resources our scene needs, turn vsync off. You can do this via Edit / Project Settings / Quality. It is found at the bottom, under the Other heading.
No more vsync.
Now you can get a better look at the CPU usage. In my case physics requires most time, followed by rendering, and then my scripts. This remains true for a long time, even though everything will slow down as the sphere count goes up.
Profiler without vsync.
There are also two unexpected observations that we can make. First, there are occasional spikes of CPU usage. Second, the memory graph shows frequent GC allocation spikes, which indicates that there is memory being allocated and subsequently freed. As we're only creating new objects and never throw anything away, this is odd.
Both phenomena are caused by the Unity editor. The CPU spikes happen whenever you select something in the editor. The memory allocations are caused by a call to GameView.GetMainGameViewRenderRect, which is invoked by the editor. There is additional overhead as well, especially if you have both the game and scene view visible at the same time. In short, the editor itself interferes with our measurements.
You can still get plenty of useful information from in-editor profiling, but if you want to eliminate the editor itself from your measurements, you have to make a standalone build. You can still use the profiler if you make a development build and even automatically connect to it when running your app. You can configure this via File / Build Settings...
build settingsprofiler
The profiler attached to a standalone app.
When profiling a standalone build, the data looks quite different. Memory allocations are now only caused by nucleons being spawned, and no more garbage collection occurs. In my case rendering takes more time, because I'm running the app full-screen instead of in a small game view. Also, the scripts are so insignificant that they're not even visible in the graph.

Measuring Frames Per Second

The profiles gives us useful information, but it still doesn't gives us a good measurement of the frame rate. The FPS numbers shows are just 1 divided by the CPU time, which is not the actual frame rate that we're getting. So let's measure it ourselves.
We need a simple component that tells us the current frames per second that our app is running at. A single public property suffices. We make it an integer because we don't really need fractional precision.
using UnityEngine;

public class FPSCounter : MonoBehaviour {

 public int FPS { get; private set; }
}
We measure the frames per second each update by dividing 1 by the time delta of the current frame. We cast the result to an integer, effectively rounding down.
 void Update () {
  FPS = (int)(1f / Time.deltaTime);
 }
However, there is a problem with this approach. The time delta is not the actual time it took to process the last frame, it is influence by the current time scale. This means that our FPS will be wrong unless the time scale is set to 1. Fortunately, we can also ask Unity for the unscaled time delta.
 void Update () {
  FPS = (int)(1f / Time.unscaledDeltaTime);
 }
Some kind of UI is needed to show the FPS. Let's use Unity's UI for that. Create a canvas with a panel inside it that in turn contains a text object. These can be added via the GameObject / UI submenu. When adding a canvas you'll also get an EventSystem object to handle user input, but we don't need that, so you can remove it.
UI object hierarchy.
I used the default canvas settings, except that I made it pixel-perfect.
A pixel-perfect canvas.
The panel is used to create a semitransparent black background for the FPS label. That way it will always be readable. I put it at the top-left corner of the window. Set its anchor to top-left so it remains in place regardless of the window's size. Set its pivot to (0,1) for easy placement.
Position the label inside the panel in a similar way. Make it white bold text, centered both horizontally and vertically. Design the whole thing so it snugly fits two digits.
panel label
panel scene label scene
Building the UI.
Now we need to bind the FPS value to the label. Let's create a component for this purpose. It needs an FPSCounter component to retrieve the value from, and a reference to a Text label from the UnityEngine.UI namespace to assign the value to.
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(FPSCounter))]
public class FPSDisplay : MonoBehaviour {

 public Text fpsLabel;
}
Add this component to our panel and hook it up. We attach it to the panel because that's our whole FPS display, not to the label. We'll include more labels later.
Setting up the display.
The display component simply has to update the label's text each frame. Let's cache the reference to the counter so we don't need to invoke GetComponent every time.
 FPSCounter fpsCounter;

 void Awake () {
  fpsCounter = GetComponent<FPSCounter>();
 }

 void Update () {
  fpsLabel.text = fpsCounter.FPS.ToString();
 }
The FPS label is now updating! But as we designed it for two digits, it will show useless values whenever our frame rate exceeds 99 per second. So let's clamp displayed value. Anything above 99 performs good enough anyway.
 void Update () {
  fpsLabel.text = Mathf.Clamp(fpsCounter.FPS, 0, 99).ToString();
 }
Now we can see the frame rate.
Everything appears to work fine now, but there is a subtle problem. We are now creating a new string object each update, which is discarded the next update. This pollutes the managed memory, which will trigger the garbage collector. While this isn't a big deal for desktop apps, it is more troublesome for devices with little memory to spare. It also pollutes our profiler data, which is annoying when you're hunting for allocations.
Temporary string objects are created each update.
Can we get rid of these temporary strings? The value that we are displaying can be any integer between 0 and 99. That's 100 different strings. Why not create all these strings once and reuse them, instead of recreating the same content all the time?
 static string[] stringsFrom00To99 = {
  "00", "01", "02", "03", "04", "05", "06", "07", "08", "09",
  "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
  "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
  "30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
  "40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
  "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
  "60", "61", "62", "63", "64", "65", "66", "67", "68", "69",
  "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
  "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
  "90", "91", "92", "93", "94", "95", "96", "97", "98", "99"
 };
 
 void Update () {
  fpsLabel.text = stringsFrom00To99[Mathf.Clamp(fpsCounter.FPS, 0, 99)];
 }
By using a fixed array of string representations of every number that we might need, we have eliminated all temporary string allocations!
unitypackage

Averaging Frames Per Second

Updating the FPS value each frame has an unfortunate side effect. The label will fluctuate constantly when the frame rate isn't stable, making it hard to get a useful reading. We could update the label only once in a while, but then we would no longer get a good impression of how the frame rate is behaving.
A possible solution is to average the frame rate, smoothing the impact of sudden changes, producing a less jittery value. Let's adjust FPSCounter so it does this over a configurable range of frames. Setting this value to 1 would be the same as not averaging at all, so it is effectively optional.
 public int frameRange = 60;
Configurable frame range.
Let's change the property name from FPS to AverageFPS, as that is a better description of the value it now represents. Either use your IDE to refactor the name, or manually update the display component to use the new name.
 public int AverageFPS { get; private set; }
Now we need a buffer to store the FPS values of multiple frames, plus an index so we know where to put the data of the next frame.
 int[] fpsBuffer;
 int fpsBufferIndex;
When initializing this buffer, make sure that frameRange is at least 1, and set the index to 0.
 void InitializeBuffer () {
  if (frameRange <= 0) {
   frameRange = 1;
  }
  fpsBuffer = new int[frameRange];
  fpsBufferIndex = 0;
 }
The Update method becomes a little more complicated. It begins by initializing the buffer if this is needed, either because we just started or because frameRange has changed. Then the buffer has to be updated, after which the average FPS can be calculated.
 void Update () {
  if (fpsBuffer == null || fpsBuffer.Length != frameRange) {
   InitializeBuffer();
  }
  UpdateBuffer();
  CalculateFPS();
 }
Updating the buffer is done by storing the current FPS at the current index, which is then incremented.
 void UpdateBuffer () {
  fpsBuffer[fpsBufferIndex++] = (int)(1f / Time.unscaledDeltaTime);
 }
But we'll quickly fill our entire buffer, and then what? We'll have to discard the oldest value before adding the new one. We could shift all values one position, but the average doesn't care about the order that the values are in. So we can just wrap the index back to the start of the array. That way we always override the oldest value with the newest, once the buffer has been filled.
 void UpdateBuffer () {
  fpsBuffer[fpsBufferIndex++] = (int)(1f / Time.unscaledDeltaTime);
  if (fpsBufferIndex >= frameRange) {
   fpsBufferIndex = 0;
  }
 }
Calculating the average is a simple matter of summing all values in the buffer and dividing by the amount of values.
 void CalculateFPS () {
  int sum = 0;
  for (int i = 0; i < frameRange; i++) {
   sum += fpsBuffer[i];
  }
  AverageFPS = sum / frameRange;
 }
Our average frame rate now works, and with a reasonable frame range it is a lot easier to get a good reading. But we can do even better. As we now have data from multiple frames, we can also expose the highest and lowest FPS in this range too. This gives us a lot more information than just an average.
 public int HighestFPS { get; private set; }
 public int LowestFPS { get; private set; }
We can find these values at the same time that we are calculating the sum.
 void CalculateFPS () {
  int sum = 0;
  int highest = 0;
  int lowest = int.MaxValue;
  for (int i = 0; i < frameRange; i++) {
   int fps = fpsBuffer[i];
   sum += fps;
   if (fps > highest) {
    highest = fps;
   }
   if (fps < lowest) {
    lowest = fps;
   }
  }
  AverageFPS = sum / frameRange;
  HighestFPS = highest;
  LowestFPS = lowest;
 }
Our FPSDisplay components can now bind two additional labels.
 public Text highestFPSLabel, averageFPSLabel, lowestFPSLabel;

 void Update () {
  highestFPSLabel.text =
   stringsFrom00To99[Mathf.Clamp(fpsCounter.HighestFPS, 0, 99)];
  averageFPSLabel.text =
   stringsFrom00To99[Mathf.Clamp(fpsCounter.AverageFPS, 0, 99)];
  lowestFPSLabel.text =
   stringsFrom00To99[Mathf.Clamp(fpsCounter.LowestFPS, 0, 99)];
 }
Add two more labels to the UI and hook them all up. I put the highest FPS at the top and the lowest FPS at the bottom, with the average FPS in the middle.
hierarchy component scenegame
More information, less jitter.
unitypackage

Coloring the Labels

As a final touch to the FPS labels, we can colorize them. This can be done by associating colors with FPS values. Such an association can be represented with a custom struct.
 [System.Serializable]
 private struct FPSColor {
  public Color color;
  public int minimumFPS;
 }
As FPSDisplay is the only thing that will use this structure, we put the struct definition directly inside that class and make it private so that it won't show up in the global namespace. Make it serializable so that it can be exposed by the Unity editor.
Now add an array of these struct so we can configure the coloring of the FPS labels. We'd typically add a public field for that, but we can't do that because the struct itself is private. So make the array private as well and give it the SerializeField attribute so Unity exposes it in the editor and saves it.
 [SerializeField]
 private FPSColor[] coloring;
Go ahead and add some colors! Make sure that there is at least one entry, order them from highest to lowest FPS, with the last entry for 0 FPS.
Coloring.
Before applying the colors to the labels, restructure the Update method by introducing a separate Display method that takes care of adjusting a single label.
 void Update () {
  Display(highestFPSLabel, fpsCounter.HighestFPS);
  Display(averageFPSLabel, fpsCounter.AverageFPS);
  Display(lowestFPSLabel, fpsCounter.LowestFPS);
 }

 void Display (Text label, int fps) {
  label.text = stringsFrom00To99[Mathf.Clamp(fps, 0, 99)];
 }
The correct color can be found by looping through the array until the minimum FPS for a color is met. Then set the color and break out of the loop.
 void Display (Text label, int fps) {
  label.text = stringsFrom00To99[Mathf.Clamp(fps, 0, 99)];
  for (int i = 0; i < coloring.Length; i++) {
   if (fps >= coloring[i].minimumFPS) {
    label.color = coloring[i].color;
    break;
   }
  }
 }
Colored fps labels.
Done! Enjoy watching your FPS tank, in color!

Friday, March 3, 2017

#9 Construct a Fractal


Constructing a Fractal

 
Details Through Recursion
  • Instantiate game objects.
  • Work with recursion.
  • Use coroutines.
  • Add randomness.

Fractals are intriguing and often beautiful. In this tutorial we'll write a small C# script that manifests some fractal-like behavior.
You're assumed to know your way around Unity's editor and know the basics of creating C# scripts. If you've completed the Clock tutorial then you're good to go.

You'll create randomized 3D fractals.

How to Make a Fractal

We are going to create a 3D fractal. We use the concept that the details of a fractal can look exactly like the whole thing. We can apply this to an object hierarchy in Unity. Start with some root object, then add children to it that are smaller but otherwise identical. Doing this by hand would be cumbersome, so we'll create a script to do it for us.
Start with a new project and a new scene. I put a directional light in there and moved the camera to a more interesting angle, but you can set it up as you please. I also went ahead and created a material to use for the fractal later. It simply uses the specular shader with default settings, which is just a bit more pleasing to look at than the default diffuse one.
Create a new empty game object and place it at the origin. This will be the base of our fractal. Then create a new C# script named Fractal and add it to the object.
using UnityEngine;
using System.Collections;

public class Fractal : MonoBehaviour {

}
Project setup.
unitypackage

Showing Something

What will our fractal look like? Let's make it configurable by adding a public mesh and material variable to our Fractal component script. We then insert a Start method in which we add a new MeshFilter component and a new MeshRenderer component. At the same time, we directly assign our mesh and material to them.
using UnityEngine;
using System.Collections;

public class Fractal : MonoBehaviour {
 
 public Mesh mesh;
 public Material material;

 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
 }
}
Now we can assign our custom material to the fractal component. Also assign a mesh by clicking on the dot next to the property and selecting Unity's default cube from the popup. After doing so, a cube will show up when we enter play mode.
Of course we could have also added the components manually, but we're creating a fractal here.
inspector in edit mode inspector in play modecube in play mode
Components appear in play mode.
unitypackage

Making Children

How do we create the children of this fractal? The easiest way is to just go ahead and make one in Start by creating a new game object and adding a Fractal component to it. Try it, hit play, and quickly exit play mode again.
 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
  new GameObject("Fractal Child").AddComponent<Fractal>();
 }
The problem is that every new fractal instance will create yet another one. This happens each frame, without end. Let it run for a while and your computer will get into trouble as it runs out of memory. Typically recursive algorithms that don't stop will consume your machine's resources almost instantly and result in either a stack overflow exception or a crash. In this case it is a rather benign explosion, because it happens slowly.
To prevent this from happening, we introduce the concept of a maximum depth. Our initial fractal instance will have a depth of zero. It's child will have a depth of one. The child of this child will have a depth of 2. And so on, until the maximum depth is reached.
Add a public maxDepth integer variable and set it to 4 in the inspector. Also add a private depthinteger. Then only create a new child if we are below the maximum depth.
What will happen when we enter play mode now?
 public int maxDepth;

 private int depth;

 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
  if (depth < maxDepth) {
   new GameObject("Fractal Child").AddComponent<Fractal>();
  }
 }
Maximum depth.
Exactly one child got created. Why? Because we never gave depth a value, it's always zero. Because zero is less than 4, our root fractal object created a child. The child's depth value is also zero. However, we never set the child's maxDepth either, so it is also zero. Therefore the child did not create another one.
Besides that, the child also lacks a material and a mesh. We need to copy these references from its parent. Let's add a new method that takes care of all the necessary initializations.
 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
  if (depth < maxDepth) {
   new GameObject("Fractal Child").
    AddComponent<Fractal>().Initialize(this);
  }
 }
 
 private void Initialize (Fractal parent) {
  mesh = parent.mesh;
  material = parent.material;
  maxDepth = parent.maxDepth;
  depth = parent.depth + 1;
 }
When we enter play mode this time, four children will be created, as was expected. But they're not really children, as they all appear in the hierarchy root. The parent–child relationship between game objects is defined by their transformation hierarchy. So a child needs to make the parent of it's transform component equal to it's fractal parent's transform.
 private void Initialize (Fractal parent) {
  mesh = parent.mesh;
  material = parent.material;
  maxDepth = parent.maxDepth;
  depth = parent.depth + 1;
  transform.parent = parent.transform;
 }
children without nesting children with nesting
Children, without and with nesting.
unitypackage

Shaping Children

So far the children are superimposed on their parent, which means we still only see a single box. We need to move them inside their local space so that they become visible. And because they are supposed to be smaller than their parent, we have to scale them down too.
First the scaling. How much? Let's make it configurable with a new variable named childScale and assign it a value of 0.5 in the inspector. Don't forget to pass this value from parent to child as well. Then use it to set the child's local scale.
Next, where shall we move the children? Let's simply move them straight up, so that they touch their parent. We assume that the parent has a size of one in all directions, which is true for the cube that we're using. Moving up by a half puts us at the point where parent and child should touch. So we have to move an additional amount equal to half the size of the child.
 public float childScale;

 private void Initialize (Fractal parent) {
  mesh = parent.mesh;
  material = parent.material;
  maxDepth = parent.maxDepth;
  depth = parent.depth + 1;
  childScale = parent.childScale;
  transform.parent = parent.transform;
  transform.localScale = Vector3.one * childScale;
  transform.localPosition = Vector3.up * (0.5f + 0.5f * childScale);
 }
inspector child scale of 0.5child scale comparison
Child scale of 0.5, and from 0.3 to 0.7 for comparison.
unitypackage

Making Multiple Children

What we are creating now looks like a tower, but not really a fractal. We need it to branch, by creating multiple children per parent. It is easy to just create a second object, but it also has to grow in a different direction. So let's add a direction parameter to our Initialize method and use that to position the second child to the right instead of up.
 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
  if (depth < maxDepth) {
   new GameObject("Fractal Child").AddComponent<Fractal>().
    Initialize(this, Vector3.up);
   new GameObject("Fractal Child").AddComponent<Fractal>().
    Initialize(this, Vector3.right);
  }
 }

 private void Initialize (Fractal parent, Vector3 direction) {
  …
  transform.localPosition = direction * (0.5f + 0.5f * childScale);
 }
Two children per parent.
This is starting to look more like it! Do you still understand in what order the cubes have been created? As they're all created in a few frames, it goes too fast for us to see it grow. I think it's fun to slow this process down so we can watch it happen. We can do this by using a coroutine to create the children.
Think of coroutines as methods in which you can insert pause statements. While the method invocation is paused, the rest of the program continues. Though this point of view is too simplistic, it is all we need to make use of it right now.
Move the two child creation lines to a new method named CreateChildren. This method needs to have IEnumerator as a return type, which exists in the System.Collectionsnamespace. That's why Unity includes it in their default script template and why I included it in the beginning as well.
Instead of just calling this method in Start, we have to call it as an argument for Unity's StartCoroutine method.
Then add a pause directive before creating each child. Do this by creating a new WaitForSeconds object for half a second or so, then yielding it back to Unity.
 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
  if (depth < maxDepth) {
   StartCoroutine(CreateChildren());
  }
 }

 private IEnumerator CreateChildren () {
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").
   AddComponent<Fractal>().Initialize(this, Vector3.up);
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").
   AddComponent<Fractal>().Initialize(this, Vector3.right);
 }
Now we can watch it grow! Did you see a problem in the way it did? Let's add a third child per parent, this time on the left side.
 private IEnumerator CreateChildren () {
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").
   AddComponent<Fractal>().Initialize(this, Vector3.up);
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").
   AddComponent<Fractal>().Initialize(this, Vector3.right);
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").
   AddComponent<Fractal>().Initialize(this, Vector3.left);
 }
three children three children with overdraw
Three children per parent, normal and overdraw vision.
The problem is that the children have the same orientation as their parent. This means that a left child whose parent is itself a right child will find itself inside its grandparent, and vice versa. To solve this, we have to rotate the children so that their upward direction will point away from their parent.
We will solve this by adding an orientation parameter to Initialize. It will be a quaternion used to set the local rotation of the new child. The upward child needs no rotation, the right child needs to rotation 90 degrees clockwise, and the left child needs to rotate in the opposite direction.
 private IEnumerator CreateChildren () {
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").AddComponent<Fractal>().
   Initialize(this, Vector3.up, Quaternion.identity);
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").AddComponent<Fractal>().
   Initialize(this, Vector3.right, Quaternion.Euler(0f, 0f, -90f));
  yield return new WaitForSeconds(0.5f);
  new GameObject("Fractal Child").AddComponent<Fractal>().
   Initialize(this, Vector3.left, Quaternion.Euler(0f, 0f, 90f));
 }
 
 private void Initialize (Fractal parent,
                          Vector3 direction,
                          Quaternion orientation) {
  …
  transform.localRotation = orientation;
 }
three children rotated three children rotated with overdraw
Three children per parent, now rotated.
Now that the children are rotated, they no longer immediately grow back into the fractal. But you might have noticed that some of the smallest children still end up disappearing into the root cube. This happens because with a scaling factor of 0.5, this fractal will self-intersect in four steps. You can reduce the scaling to solve this problem, or use spheres instead of cubes.
spheres spheres with overdraw
Spheres don't self-intersect with a child scale of 0.5.
unitypackage

Better Code For More Children

Our code has become a bit unwieldy. Let us generalize by moving the direction and orientation data to static arrays. Then we can reduce CreateChildren to a short loop and use the child index as a parameter for Initialize.
 private static Vector3[] childDirections = {
  Vector3.up,
  Vector3.right,
  Vector3.left
 };

 private static Quaternion[] childOrientations = {
  Quaternion.identity,
  Quaternion.Euler(0f, 0f, -90f),
  Quaternion.Euler(0f, 0f, 90f)
 };

 private IEnumerator CreateChildren () {
  for (int i = 0; i < childDirections.Length; i++) {
   yield return new WaitForSeconds(0.5f);
   new GameObject("Fractal Child").AddComponent<Fractal>().
    Initialize(this, i);
  }
 }

 private void Initialize (Fractal parent, int childIndex) {
  …
  transform.localPosition =
   childDirections[childIndex] * (0.5f + 0.5f * childScale);
  transform.localRotation = childOrientations[childIndex];
 }
Now let's introduce two more children by simple adding their data to the arrays. One going forward, the other going backward.
 private static Vector3[] childDirections = {
  Vector3.up,
  Vector3.right,
  Vector3.left,
  Vector3.forward,
  Vector3.back
 };

 private static Quaternion[] childOrientations = {
  Quaternion.identity,
  Quaternion.Euler(0f, 0f, -90f),
  Quaternion.Euler(0f, 0f, 90f),
  Quaternion.Euler(90f, 0f, 0f),
  Quaternion.Euler(-90f, 0f, 0f)
 };
Five children per parent, the full fractal.
We now have the full fractal structure. But what about the underside of the root cube? The idea is that the fractal is growing out of something, like a plant. Although I won't, if you want to, you could add a special sixth child going downward that's only added to the root node. Adding it to all nodes would be a waste, because it would grow directly into its grandparent.
unitypackage

Explosive Growth

How many cubes are we actually creating? As we're always creating five children per parent, the total number of cubes when fully grown will depend on the maximum depth. A maximum depth of zero produces only one cube, the initial root. A maximum depth of one produces five additional children, for a total of six cubes. As it is fractal, this pattern repeats and we can write it as the function f(0) = 1, f(n) = 5 × f(n - 1) + 1.
The above function produces the sequence 1, 6, 31, 156, 781, 3906, 19531, 97656, and so on. You will see these numbers show up as the amount of draw calls in the game view statistics of Unity. If you have dynamic batching enabled, it will be the sum of Draw Calls and Saved by batching.
Unity will probably be able to handle a maximum depth up to four or five. Any higher and your frame rate will become horrible.
Besides quantity, duration is also an issue. Right now we're pausing half a second before creating a new child. This produces synchronized bursts of growth for a few seconds. We could distribute the growth more evenly by randomizing the delays. This also results in a more unpredictable and organic pattern that I find more fun to watch.
So let's replace the fixed delay with a random range between 0.1 and 0.5. I also increased the maximum depth to 5 to make the effect more noticeable.
 private IEnumerator CreateChildren () {
  for (int i = 0; i < childDirections.Length; i++) {
   yield return new WaitForSeconds(Random.Range(0.1f, 0.5f));
   new GameObject("Fractal Child").AddComponent<Fractal>().
    Initialize(this, i);
  }
 }
unitypackage

Adding Color

The fractal is a little dull. Let's liven it up by adding some color variation. We do this by interpolating from white at the root to yellow at the smallest children. The static Color.Lerpmethod is a handy way to do this. The interpolator goes from zero to one, which we do by dividing our current depth by the maximum depth. Because we don't want an integer division here, we convert depth to a float first.
 private void Start () {
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = material;
  GetComponent<MeshRenderer>().material.color =
   Color.Lerp(Color.white, Color.yellow, (float)depth / maxDepth);
  if (depth < maxDepth) {
   StartCoroutine(CreateChildren());
  }
 }
Colored, but no dynamic batching.
This already looks a lot more interesting! But another thing happened as well. Dynamic batching used to work, but now it doesn't. How do we fix this?
The problem is that by adjusting the color or a child's material we silently created a duplicate of that material. This is necessary because otherwise everything using that material would end up with the same color. However, batching only works when the exact same material is used for multiple items. Equivalence is not checked – that would be too expensive to do – it must really be the same material.
Let's create only one material duplicate per depth instead of per cube. Add a new array field to hold the materials. Then check whether an array exists in Start and if not call a new InitializeMaterials method. In this method we will explicitly duplicate our material and change its color per depth.
 private Material[] materials;

 private void InitializeMaterials () {
  materials = new Material[maxDepth + 1];
  for (int i = 0; i <= maxDepth; i++) {
   materials[i] = new Material(material);
   materials[i].color =
    Color.Lerp(Color.white, Color.yellow, (float)i / maxDepth);
  }
 }
 
 private void Start () {
  if (materials == null) {
   InitializeMaterials();
  }
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material = materials[depth];
  if (depth < maxDepth) {
   StartCoroutine(CreateChildren());
  }
 }
Now instead of passing the material reference from parent to child, pass the materials array reference instead. If we didn't, each child would be forced to create its own materials array and we wouldn't have solved the problem.
 private void Initialize (Fractal parent, int childIndex) {
  mesh = parent.mesh;
  materials = parent.materials;
  …
 }
Colored, now with dynamic batching.
We have our batching back, and it makes quite a difference in this case! The color is still not that interesting though. A nice tweak is to give the deepest level a radically different color. This can reveal patterns in the fractal that you might not have noticed before.
Simply change the last color to magenta afterwards. Also adjust the interpolator so that we still see the full transition to yellow. And while we're at it, squaring it results in a slightly nicer transition.
 private void InitializeMaterials () {
  materials = new Material[maxDepth + 1];
  for (int i = 0; i <= maxDepth; i++) {
   float t = i / (maxDepth - 1f);
   t *= t;
   materials[i] = new Material(material);
   materials[i].color = Color.Lerp(Color.white, Color.yellow, t);
  }
  materials[maxDepth].color = Color.magenta;
 }
Now with magenta tips.
Let's add a second color progression, say from white to cyan with red tips. We'll use a single two-dimensional array to hold them both, then select one at random when we need a material. This way our fractal will look different each time we enter play mode. Feel free to add a third progression if you like.
 private Material[,] materials;

 private void InitializeMaterials () {
  materials = new Material[maxDepth + 1, 2];
  for (int i = 0; i <= maxDepth; i++) {
   float t = i / (maxDepth - 1f);
   t *= t;
   materials[i, 0] = new Material(material);
   materials[i, 0].color = Color.Lerp(Color.white, Color.yellow, t);
   materials[i, 1] = new Material(material);
   materials[i, 1].color = Color.Lerp(Color.white, Color.cyan, t);
  }
  materials[maxDepth, 0].color = Color.magenta;
  materials[maxDepth, 1].color = Color.red;
 }
 
 private void Start () {
  if (materials == null) {
   InitializeMaterials();
  }
  gameObject.AddComponent<MeshFilter>().mesh = mesh;
  gameObject.AddComponent<MeshRenderer>().material =
   materials[depth, Random.Range(0, 2)];
  if (depth < maxDepth) {
   StartCoroutine(CreateChildren());
  }
 }
Randomized colors.
unitypackage

Randomizing Meshes

Besides colors, we also also randomly choose which mesh to use. Let's replace our public mesh variable with an array and pick one out of it at random in Start.
 public Mesh[] meshes;
 
 private void Start () {
  if (materials == null) {
   InitializeMaterials();
  }
  gameObject.AddComponent<MeshFilter>().mesh =
   meshes[Random.Range(0, meshes.Length)];
  gameObject.AddComponent<MeshRenderer>().material =
   materials[depth, Random.Range(0, 2)];
  if (depth < maxDepth) {
   StartCoroutine(CreateChildren());
  }
 }

 private void Initialize (Fractal parent, int childIndex) {
  meshes = parent.meshes;
  …
 }
If we were to put only a single cube in our new array property in the inspector, then the result would be the same as before. But add a sphere and you suddenly get a 50% chance of spawning either a cube or a sphere per element of the fractal.
Fill this array however you like. I put the sphere in there twice so it is twice as likely to be used as the cube. You can also add other meshes, though capsules and cylinders don't work so well because they're elongated.
inspectorrandom meshes
Randomly choosing between a cube and a sphere.
unitypackage

Making the Fractal Irregular

Our fractal is nice and complete, but we can make it a bit more organic by cutting off some of its branches. We do that by introducing a new public spawnProbability variable. We pass it along and use it to randomly determine whether we spawn a child or skip it. A probability of 0 means that no children will spawn at all, while a probability of 1 means that all children will spawn. Even values a little below one could drastically alter the shape of our fractal.
The static Random.value property produces a random value between zero and one. Comparing it to spawnProbability tells us whether we should create a new child or not.
 public float spawnProbability;

 private IEnumerator CreateChildren () {
  for (int i = 0; i < childDirections.Length; i++) {
   if (Random.value < spawnProbability) {
    yield return new WaitForSeconds(Random.Range(0.1f, 0.5f));
    new GameObject("Fractal Child").AddComponent<Fractal>().
     Initialize(this, i);
   }
  }
 }

 private void Initialize (Fractal parent, int childIndex) {
  …
  spawnProbability = parent.spawnProbability;
  …
 }
inspectorirregular growth
A 70% spawn chance produces irregular shapes.
unitypackage

Rotating the Fractal

All this time our fractal has been a good boy and stayed motionless. But a little movement would make it a lot more interesting to watch. Let's add a very simple Update method that rotates around the current Y axis at a speed of 30 degrees per second.
 private void Update () {
  transform.Rotate(0f, 30f * Time.deltaTime, 0f);
 }
With this simple addition all the fractal's parts are now merrily spinning. All at the same speed. Yes, let's randomize it! And make the maximum speed configurable too.
Note that we have to initialize our rotation speed in Start – not in Initialize – because the root element should rotate too.
 public float maxRotationSpeed;
 
 private float rotationSpeed;

 private void Start () {
  rotationSpeed = Random.Range(-maxRotationSpeed, maxRotationSpeed);
  …
 }

 private void Initialize (Fractal parent, int childIndex) {
  …
  maxRotationSpeed = parent.maxRotationSpeed;
  …
 }
 
 private void Update () {
  transform.Rotate(0f, rotationSpeed * Time.deltaTime, 0f);
 }
Configured for speed.
unitypackage

Adding More Chaos

Are there more adjustments that we could do to throw our fractal out of whack in subtle ways? There are many! One of them is to knock the fractal's elements out of alignment by adding a subtle rotation. Let's call it twist.
 public float maxTwist;

 private void Start () {
  rotationSpeed = Random.Range(-maxRotationSpeed, maxRotationSpeed);
  transform.Rotate(Random.Range(-maxTwist, maxTwist), 0f, 0f);
  …
 }

 private void Initialize (Fractal parent, int childIndex) {
  …
  maxTwist = parent.maxTwist;
  …
 }
inspectorsome twist
Some nice twist.
Another option would be to mess with the child scale. Or maybe skip a depth sometimes. Fiddle with positions? From this point I leave it up to you!