All posts in "Unity3D"

7 VR / VIVE Games – Day 2 – Archery

HTC VIVE Game Challenge

This week, I’ve decided to start a new VIVE challenge.  Each day, I’ll be creating a new Unity game developed specifically for the HTC VIVE.

I’ll spend a single day on each game (really about 4-6h of a day), creating the base gameplay and polishing up the experience a

After each game is complete, I’ll post the results here with a gameplay video and some thoughts on how it worked out.  I’ll also provide a download link for any current Vive owners to try it out and see how the experiences turn out.


Game 2 is ready now!

VIVE – Archery

The goal for this game was to build a semi-realistic archery simulator.  It didn’t quite turn out that way, but it’s still an interesting experiment.

Each round, you receive 10 arrows.  Your goal is to score as many points as you can by hitting both stationary and moving targets.





In my head, this was a lot more fun than it turned out to be.  I’ve learned that holding something in front of your head in VR doesn’t feel great.  I think the lack of peripheral vision may be the reason for this.  While it was a neat experiment, I think in the future, I’ll avoid games that have mechanics like this.

Bow & arrow pulling also turned out to be a little more time consuming than I initially expected.  While I could get the arrow to stick to the string pretty easily, making that look right and have proper limits wasn’t feasible in such a short time.  In the end, I went with making the bow play it’s normal pull animation when you touch the string and removing the restriction of holding the arrow in place.  So while in the video it may look like it’s being pulled back and released, you can just as easily tap the string and pull the arrow controller away.  I think the lack of a proper physical feedback mechanism (like a bow built for VR) makes this interaction just not quite work.

All that said, my wife somehow still enjoyed the game.  It was one of her recommendations, so perhaps that had some influence.  Or maybe I’m just not great at judging these, I’m not sure yet.


There are only a few components to this game.  The more advanced ones got pulled due to not working out (bow pulling)Scene View

As a side note, I do have a Giveaway going on right now for a $25 Asset Store voucher.  If you want to win, you can enter here.


This was an asset from the Asset Store for $5.  There’s also a free one available, but in the end I wanted the animation so I paid up.


It works by having a trigger on a box collider attached to the string.  When the trigger is entered by the right hand controller, I reload the arrow and play the animation.Archery - Hierarchy


The arrow was pulled off the bow asset and the pivot point had to be fixed.  For some reason, many art assets in the store have strange offsets and pivots that make no sense, this followed that trend.  Once it was fixed though, I placed a simple arrow script and an audio source on the arrow.  The script has a single public Fire method that sets its’ parent to the root (initially the parent is the bow so it will track), then it adds some force in it’s forward direction.  Because the bow’s forward was a bit messed up, I threw in a quick hack of an extra gameObject named “DirectionalTransform” that I used to get the correct forward direction (this could have been done in max/maya too, but a lot of the time these little hacks are quicker for people who haven’t used them much before).

Archery - Bow InspectorArchery - Bow Inspector

Archery – Bow Inspector

They also check for collision and if they hit the ground or a target/box I set the isKinematic property to true on it’s rigidbody so it appears to stick into the target.  You may notice in the video that there’s a bug when she hits the moving targets.  I didn’t think to make the arrows become a child of the target, so they stay floating wherever they hit it.  I considered fixing this, but thought it was more interesting to discuss the issue than resolve it.

Boxes & Targets

Moving Target

Moving Target

These just have a trigger collider and a “Target” script.  The target script just watches for trigger enter events.  When they fire, it increments the score and plays a sound.





Up Tomorrow: Zombie Shooter


Continue reading >

7 VR / VIVE Games in 7 Days

HTC VIVE Game Challenge

This week, I’ve decided to start a new VIVE challenge.  Each day, I’ll be creating a new Unity game developed specifically for the HTC VIVE.

I’ll spend a single day on each game (really about 4-6h of a day), creating the base gameplay and polishing up the experience a

After each game is complete, I’ll post the results here with a gameplay video and some thoughts on how it worked out.  I’ll also provide a download link for any current Vive owners to try it out and see how the experiences turn out.


The first game in the list is ready now….

VIVE – Dungeon Defense

In this game, you play as a magic sky wizard presiding over a dungeon full of treasure.

Your goal is simple, fight off the invading goblins with your magic wands for as long as you can.

They’ll keep invading until they steal all your gold.




I really like the view in this game.  Standing over a world full of miniatures is a really interesting feeling and I think is one of my favorite ways to experience VR.
I noticed this at Oculus Connect too when they had the long CV1 demos.  One of the key demos that stood out to me was a tiny city that you could see but not interact with.

The mechanics of shooting things is pretty basic, but that helps new players get in and understand what to do quickly.

I found myself getting really low a few times to get a close up view of the little goblins I was destroying.  I think with some polish, this could be a fun little game, but I’m certain it’s lacking something key gameplay wise to make it great.


This game has some pretty basic systems that run it.


The Goblins spawn from hidden spawnpoints (you could see them if you walk over to them).  Each of them is assigned a target destination that they walk toward (the chests).  When they reach the chest, they cause a Trigger event to happen that plays some sound, poofs the goblin, and reduces your remaining gold by 1.

Dungeon Defense - Spawner

Dungeon Defense – Spawner


Dungeon Defense - Camera Rig

The wands are from a pack on the asset store I grabbed for a few $.  I put a sphere on them with some random particle material that grows to full size based on the amount of time left in their refresh timers.  The refresh on them is controlled by a simple float that I tweaked in the editor until it felt right.  Each wand has a projectile prefab assigned that they spawn and launch forward using the physics system on the Rigidbody.  When they collide with anything other than the wands, they destroy themselves, spawn an impact particle, and do a quick SphereOverlap to find any Goblins within range to destroy.  Dungeon Defense - Wand Script



The last thing I want to explain is how to scale the world.  In this demo, the world was all built at normal scale.  Getting the miniaturized effect was as simple as scaling up the [CameraRig] 10x.  Amazingly, that worked fine with no other alterations to the game..

Baseball Home Run Derby

Also interested in a Baseball / Home Run Derby Game?
Check out my Baseball game on Steam now
<iframe src=”” width=”646″ height=”190″ frameborder=”0″></iframe>

Up Tomorrow: Archery


Continue reading >

Vive Baseball – Home Run Derby – On Greenlight

If you’ve visited this site before, you know that about a week and a half ago Valve sent out Vive headsets to attendees of the Vision Summit.

Since then, I’ve been hacking away to make some demos & tutorials for all of you.

In that process, I came across a prototype that appeared to be a lot of fun, so I polished it up and turned it into a real game.

It’s up on Steam Greenlight now for you to check out. (And please vote for it if you like it)




If you happen to have a Vive Pre and want to try it out now, send me an email using the Contact/Question form below.


Description (Pulled from my steam page)

Vive Baseball – Home Run Derby is an exciting active baseball simulator for the Vive.
Challenge your friends and family to see who can get the most home runs before the timer runs out.
There are 3 difficulty levels, from easy (for chickens) to pro.
Do well and the crowd will cheer. Try to bunt and get booed out of the stadium!
There are a variety of bats to choose from, both wooden and aluminum.
You can play at night, during the day, or even on another planet!

It’s a lot of fun, and can be a great workout as well.
Grab it now and see how many Home Runs you can hit!



Continue reading >

Vive – First Impressions & Reviews

It’s Here

If you’ve been following VR news, you know that valves Gabe Newell announced at the vision summit that they’d be giving all attendees a free Vive PRE.
Today, it arrived, and I have to say it’s pretty amazing.


It came in a giant box that contained many more boxes





The packaging was great and definitely kept the Vive safe.


Once it was all opened, you can see there is a whole lot included.

One key differentiation from the Oculus is the inclusion of hand controllers.  They’re extremely accurate, even showing the exact point on the touch pad that you’re touching.

During the tutorial, you can get a great feel of how well they’re tracked, while you inflate colored balloons and smack them around.

The Games

Some of the games/experiences were not playable with my current video card.  This isn’t the fault of the games as I’m using an AMD 280x which is at the low end for compatibility.  I plan to upgrade to the 970gtx soon and re-try those ones.  If you plan on getting a Vive, make sure to also budget for a high end video card to keep the experiences enjoyable.

Valve also included a Steam key for a set of games to try out.

This is a list of the games included free with the Vive.

I’ve included a quick description of each game and a little feedback for each.


8i – Gladiator / Message To the Future / The Climb / Wasteland

These unfortunately all ran too slow and choppy for anyone to enjoy.  This is probably because the video card (Radeon 280x) is a bit too slow.  It’s time to upgrade and try again next week.  It does seem like they have a streamlined video player though and could be promising.

Abbot’s Book Demo

I only tried this once, but the control scheme (warping around in the direction you’re facing) just didn’t feel right to me.  I understand what they’re trying to do, it just didn’t feel too natural in VR after so many other experiences where I walk around freely.

greenthumbupArpeture Robot Repair

Arpeture Robot Repair

Arpeture Robot Repair

[Warning: Complete spoilers]

This was made by Valve and quite a bit of fun.  It’s a fun/funny experience where you “attempt” to fix a robot and fail miserably.  It requires a bit of space or some awkward controls if you don’t have the space, but overall everyone who tried it thought it was enjoyable.

Cloudlands: VR Minigolf

This game also appeared to suffer from my weak video card.  Nobody was able to even hit the ball.  It seems like a neat idea, but not until I upgrade hardware.

greenthumbupFantastic Contraption

Vive is Here - Fantastic Contraption

Fantastic Contraption

This was my wifes #2 game.  In it, you build contraptions in 3D as the name implies.  One of the first things she built was a car which was fun to watch.

Felt Tip Circus

This was an interesting set of mini-games where you start above a play sized circus in a room, then dive down into it and experience parts from inside.  The mini-games were pretty fun, but the interface for moving between them could be simplified / less confusing.

greenthumbupFinal Approach

Final Approach

Final Approach!finalapproach/c3ng

This is a VR take on the Flight Control game that was popular on mobile/steam.  It also mixed in some mini-games (putting out fires, removing seagulls) that made it interesting.  There was a bit of humor, and it was pretty forgiving on failures.  It’s definitely one of the most polished experiences available with the release.  Overall it was a hit with everyone who tried it.  The menu system however isn’t very intuitive (hold the trigger before touching buttons if you want to click them).


This is a scifi shooting game.  It’s got decent graphics and some interesting mechanics, but performance with my system was too slow to be enjoyable.  Once I’ve upgraded, I think this may be a great game.

greenthumbupJob Simulator Demo

vive is here - job simulator

Job Simulator

I saw the guys who made this do a presentation at the Vision Summit.  They’ve done a great job really polishing the experience and making it fun / hilarious.  Everyone who played it wanted to do a repeat, so I’d say it was a hit.

greenthumbupNinja Trainer Vive Demo

Ninja Trainer

Ninja Trainer

It’s fruit ninja in VR…. This so far has been the most popular and requested game played.  We’ve had competitions for high scores (110 is the current btw).  I’d rate this as the #1 game/experience included.

Sisters – Scary

This was a horror/jump experience.  It’s really polished and scared two teenagers out before the halfway point.  My wife is the only one who made it through the entire thing so far, and she even let out a scream & jump at the end.  Just be sure to actually look around at stuff as it seems progression is based on interaction not time.

greenthumbupSpace Pirate Trainer VR – The boys loved it

Space Pirate

Space Pirate

You shoot at space pirates with guns.  With shields and time scale adjustment there’s enough to keep the 2 boys playing over and over.  Definitely worth a shot if you want to aim and shoot at stuff.


An underwater experience where you see beautiful imagery of sea life swimming around you.  It seems to be a relaxing passive experience with really nice art.

greenthumbupTilt Brush

Tilt Brush

Tilt Brush

This was a pretty amazing art experience.  It turns your controllers into a 3D paint brush and a pallet.  You can draw whatever you want in 3D.  While the creations we made weren’t anything impressive outside VR, when you see them in the headset it’s mind blowing.


And the Reviews

I let my family go through the experiences and gathered some feedback.
Here are their ages and favorites:

Boy #1 – 7 years old

Favorite – Space Pirates

Runner Up – Ninja Trainer

Boy #2 – 13 years old

Favorite – Space Pirates

Runner Up – Job Simulator

Girl #1 – 15 years old

Favorite – “I don’t know stop asking me”  (I think this means Final Approach)

Runner Up – “OMG I don’t know stop asking me”  (Could not translate this one)


Favorite – Ninja Trainer

Runner Up – Fantastic Contraption


Favorite – Ninja Trainer

Runner Up – Tilt Brush


Unity Integration

This post won’t cover Unity integration with the Vive, but an upcoming one will.  If you’re interested in learning how to create your own Vive games, sign up now to be notified when the first sample is available.


Continue reading >

Upcoming Presentation – Intro to Unity – March 8th – Ontario, CA

If you’re in the area, come check out my talk on March 8th!

Intro to Unity 2D, 3D, VR, & AR with Jason Weimann

Tuesday, Mar 8, 2016, 6:30 PM

CoStar Group
901 via Piemonte Suite 450 Ontario, CA

18 Nerds Attending

Intro to Unity 2D, 3D, VR, & AR  ————————————————————-Unity3D is a state of the art rendering and game engine that allows you to write your code in C#.  While the most common use is for game development, it’s also great for a variety of business applications from highly interactive cross platform GUIs to aug…

Check out this Meetup →

Continue reading >

Dependency Injection and Unit Testing Unity

This post will be the first in what will likely be a long series. Dependency Injection and Unit Testing are generally considered staples in modern software development. Game development for a variety of reasons is one of the few areas where this isn’t true. While it’s starting to become more popular, there are quite a few things holding back game programmers from embracing these valuable paradigms.

I’d like to open by giving a quick description of the benefits you’ll gain by embracing dependency injection.  Before you jump away thinking “I don’t need this” or “this will be too complicated”, just take a look at what you have to gain.  And let me try to quell any fears, this is something you can definitely take advantage of, it won’t be hard, it’ll save you time, and your code will be improved.


Benefits – What do I have to gain?

Loose Coupling

Dependency Injection by it’s nature encourages very loose coupling.  This means your objects and classes don’t have tight dependencies on other classes.  Loose coupling leads to having code that is much less rigid and brittle.

Re-usbility Across Projects

Loose coupling also makes your classes much easier to use across projects.  When your code has dependencies on many other classes or static global variables, it’s much harder to re-use that code in other projects.  Once you get into the habit of good separation and dependency injection, you’ll find that reuse becomes a near trivial task.

Encourages Coding to Interfaces

While you can certainly code to interfaces without Dependency Injection, using it will naturally encourage this behavior.  The benefits of this will become a bit more obvious in the example below, but it essentially allows you to swap behavior and systems in a clean way.

Cleaner Code

When you start injecting your dependencies, you quickly end up with less “spaghetti-code”.  It becomes much clearer what a classes job is, and how the class interacts with the rest of your project.  You’ll find that you no-longer have to worry about a minor change in one piece of code having an unexpected consequence in something that you thought would be completely unrelated.

As an example, once while working on a major AAA MMO game, I saw a bug fix to a specific class ability completely break the entire crafting system.  This exactly the kind of thing we want to avoid.

Unit Testing

This is one of the most commonly stated benefits to Dependency Injection.  While it’s a huge benefit, you can see above that it’s not the only one.  Even if you don’t plan to unit test initially (though you should),  don’t rule out dependency injection.

If you haven’t experienced a well unit tested project before, let me just say that it’s career changing.  A well tested project is less likely to slip on deadlines, ship with bugs, or fail completely.  When your project is under test, there’s no fear when you want to make a change, because you know immediately when something is broken.  You no-longer need to run through your entire game loop to verify that your changes work, and more importantly that you haven’t broken other functionality.



If it’s so good, why isn’t this common place?

Now, I’d like to cover a few of the reasons the game industry has been slow to adopt Dependency Injection & Unit Testing.


While this doesn’t apply to Unity specifically, the game industry as a whole has primarily relied on C++. There were of course studios that developed in other languages, but to this date, outside of Unity, the major engines are all C++ based. C++ has not had nearly the same movement towards Dependency Injection or Unit Testing as other common enterprise languages (Java, C#, JS, Ruby, etc).  This is changing though, and with the proliferation of unit testing and dependency injection in C#, it’s the perfect time to jump in with your games.


Dependency Injection adds overhead to your game. In the past, that overhead could be too much for the hardware to handle.  Given the option between 60fps and dependency injection, 60fps is almost always the correct answer.  Now though, hardware is really fast, and 99% of games can easily support Injection without giving up any performance.


While there are countless other “reasons” you could come across from game programmers, the key one is just an issue of mindset.  Too many people have been programming without Injection and Unit testing and just haven’t been exposed to the benefits.  They think “that’s for enterprise software”, “that’s something web developers do”, or “that doesn’t work for games”.  My goal here is to convince you that it’s worth trying.  I promise if you dig in and try dependency injection and unit testing, you’ll quickly start to see the benefits, and you’ll want to spread the word as well.


Dependency Injection Frameworks

When you’re searching, you may also see the DI frameworks referred to as IOC containers.

You may be wondering how you get started with Dependency Injection in Unity.  It’s not something built into the Unity engine, but there are a variety of options to choose from on GitHub and in the Asset Store.

Personally, I’ve been using Zenject, and my samples will be done using it.  But that doesn’t mean you shouldn’t look into the other options available.


I think the description provided on the Zenject asset page does a better job describing it than I could, so here it is:

Zenject is a lightweight dependency injection framework built specifically to target Unity. It can be used to turn the code base of your Unity application into a collection of loosely-coupled parts with highly segmented responsibilities. Zenject can then glue the parts together in many different configurations to allow you to easily write, re-use, refactor and test your code in a scalable and extremely flexible way.

While I hope that after reading this series you have a good idea why you should use a dependency injection framework, and how to get started, I must highly recommend you take a look at the documentation provided on the Zenject GitHub page.

Constructor Injection

Most Dependency Injection is done via what’s called Constructor Injection.  This means that anything your class relies on outside itself is passed in via the constructor.


I want to give an example of how you’d use Constructor Injection in a more general sense before diving too deep into the differences with Unity.  What I’m presenting here is a simplified version of a game state system I’m using in a Unity project currently.

In my project, I have a variety of game state classes.  The different “GameStates” handle how the game functions at different stages throughout the game cycle.  There are game states for things like generating terrain, lost/gameover, building, attacking, and in this example, ready to start.

In the game state “ready to start“, all we want to do is wait for the user to start the game.  The game state doesn’t care how the user starts the game, only that they do.  The simplest way to implement this would be to check on every update and see if the user pressed the “Fire1” button.

It may look something like this:

using UnityEngine;

public class GameStateReadyToStart : MonoBehaviour
    void Update()
		if (Input.GetButton("Fire1"))

	private void SwitchToNextGameState()
		// Logic to go to next gamestate here

This will work, it’s simple, and quick to implement, but there are some issues with it.



  • Our gamestate is a monobehaviour so we can read the input during the update.
  • The Input logic is inside a class who’s job isn’t Input.  The gamestate should handle game state/flow, not input.
  • Changing our input logic requires us to touch the gamestate class.
  • We’ll have to add input logic to every other gamestate.
  • Input can’t be easily varied across different devices.  If we want a touch button on iPad and the A button on an xbox, we have to make bigger changes to our gamestate class.
  • We can’t write unit tests against our gamestate because we can’t trigger input button presses.

You may be thinking that’s a long list, but I guarantee there are more problems than just those.

Why not just use a Singleton?

The first answer you may come across to some of these problems is the Singleton pattern.
While it’s very popular, simple, and resolves half of our issues, it doesn’t fix the rest.
Because of that, outside the game development world, the singleton pattern is generally considered bad practice and is often referred to as an anti-pattern.


Let’s try some separation

Now, let me show you an easy way to resolve all of the problems above.

public class GameStateReadyToStart
    public GameStateReadyToStart(IHandleInput inputHandler)
		inputHandler.OnContinue += () =>

	private void SwitchToNextGameState()
		// Logic to go to next gamestate here

Here, you can see we’ve moved input handling out of the “gamestate” object into it’s own “inputHandler” class.  Instead of reading input in an update loop, we simply wait for the InputHandler to tell us when the user is ready to continue.  The gamestate doesn’t care how the user tells us to continue.  All the gamestate cares about is that the user told it to switch to the next state.  It’s now properly separated and doing only what it should do, nothing more.

The “IHandleInput” interface for this example is very simple:

using System;

public interface IHandleInput
    Action OnContinue { get; set; }

Now, if we want to switch input types across devices, we simply write different implementations of the “IHandleInput interface.
We could for example have implementations like:

  • TouchInputHandler – Continues when the user presses anything bound to “Fire1
  • GUIBasedInputHandler – Continues when the user clicks a GUI button
  • VoiceInputHandler – Continues when the user says a phrase
  • NetworkInputHandler – Continues when the user presses something on another device (think controlling a PC game with a phone)
  • TestInputHandler – Continues via a unit test designed to verify state switching doesn’t break


Time to Inject!

Now without going too much deeper into my example, you may be thinking “that’s nice, but now I have to pass in an input handler and manage that”.

This is where dependency injection comes into play.  Instead of creating your handler and passing it into the constructor, what we’ll do is Register the handler(s) we want with our Dependency Injection Container.

To do that, we need to create a new class that derives from the Zenject class “MonoInstaller

using System;
using UnityEngine;
using Zenject;
using Zenject.Commands;

public class TouchGameInstaller : MonoInstaller
    public override void InstallBindings()


In the TouchGameInstaller class, we override InstallBindings and register our 2 classes.

Line 13 simply asks the container for an instance of the game state.

This is a very simplified version of the Installer with a single game state, later parts of this series will show how we handle multiple game states.

What we’ve done here though is avoid having to manage the life and dependencies of our “gamestate” class.
The Dependency Injection Container will inspect our classes and realize that the “GameStateReadyToStart” class has a dependency on an “IHandleInput“, because the constructor has it as a parameter.
It will then look at it’s bindings and find that “IHandleInput” is bound to “TouchInputHandler“, so it will instantiate a “TouchInputHandler” and pass it into our “gamestateautomatically.

Now, if we want to switch our implementations on different devices, we simply switch our our “TouchGameInstaller” with a new installer for the device and make no changes to our GameState classes or any existing InputHandler classes.  We no longer risk breaking anything existing when we want to add a new platform.  And we can now hook up our GameState to unit tests by using an Installer that registers a TestInputHandler.


You may realize that I haven’t injected any gameobjects yet, and could be wondering how this works with monobehaviors that can’t constructors.

In the next part of this series, I’ll explain how to hook up your gameobjects and monobehaviors with the dependency injection framework and continue the example showing how the entire thing interacts.



Continue reading >

Editing Unity variables – Encapsulation & [SerializeField]

Editing Unity script variables in the Inspector – The case for Encapsulation & [SerializeField]

If you’ve read many Unity tutorials, you may already know that it’s very easy to edit your script fields in the Unity inspector.

Most Unity tutorials (including on the official page) tell you that if you have a MonoBehaviour attached to a GameObject, any public field can be edited.

While that does technically work, I want to explain why it’s not the best way to setup your scripts, and offer an alternative that I think will help you in the future.

In this article, you’ll learn how to use proper Encapsulation while still taking full advantage of the Unity Inspector.

Take a look at this “Car.cs” script.


using UnityEngine;

public class Car : MonoBehaviour
    public Tire FrontTires;
	public Tire RearTires;

	public Tire FrontRightTire;
	public Tire FrontLeftTire;
	public Tire RearRightTire;
	public Tire RearLeftTire;

	private void Start()
		// Instantiate Tires
		FrontRightTire = Instantiate(FrontTires);
		FrontLeftTire = Instantiate(FrontTires);

		RearRightTire = Instantiate(RearTires);
		RearLeftTire = Instantiate(RearTires);


If you look at the Start method, you can tell that the fields “FrontTires” & “RearTires” are referring to prefabs that will be be used to instantiate the 4 tires of the car.

Once we’ve assigned some Tire prefabs, it looks like this in the Inspector.

In play mode, the Start method will instantiate the 4 actual tires on our car and it’ll look like this.


Problem #1 – Confusion

The first thing you might realize is that there could be some confusion about which fields to assign the prefab to.
You’ve just seen the code, or in your own projects, perhaps you’ve just written it, and it may seem like a non-issue.

But if your project ever grows, it’s likely others will need to figure out the difference, and to do so, they’ll need to look at the code too.
If your project lasts more than a few days/weeks, you also may forget and have to look back through the code.

Now you could solve this with special naming.  I’ve seen plenty projects where the “Prefab” fields had a prefix or suffix like “Front Tires Prefab”.

That can also work, but then you still have 4 extra fields in there that you have to read every time.  And remember, this is a simple example, your real classes could have dozens of these fields.

Fix #1 – Let’s Use Properties for anything public

To resolve this, let’s change the entries we don’t want to be editable into Properties.

Microsoft recommends you make your fields all private and use properties for anything that is public.  There are plenty of benefits not described in this article, so feel free to read in detail from Microsofts article Fields(C# Programming Guide)

Now let’s change the “Car.cs” script to match this.
using UnityEngine;

public class Car : MonoBehaviour
    public Tire FrontTires;
	public Tire RearTires;

	public Tire FrontRightTire { get; set; }
	public Tire FrontLeftTire { get; set; }
	public Tire RearRightTire { get; set; }
	public Tire RearLeftTire { get; set; }

	private void Start()
		// Instantiate Tires
		FrontRightTire = Instantiate(FrontTires);
		FrontLeftTire = Instantiate(FrontTires);

		RearRightTire = Instantiate(RearTires);
		RearLeftTire = Instantiate(RearTires);

Here’s what it looks like in the Inspector

With that change, you may be thinking we’ve resolved the issue and everything is good now.
While it’s true that confusion in the editor is all cleared up, we still have one more problem to address.
That problem is lack of Encapsulation.


Problem #2 – No Encapsulation

“In general, encapsulation is one of the four fundamentals of OOP (object-oriented programming). Encapsulation refers to the bundling of data with the methods that operate on that data.”

There are countless articles and books available describing the benefits of encapsulation.

The key thing to know is that properly encapsulated classes only expose what’s needed to make them operate properly.

That means we don’t expose every property, field, or method as public.
Instead, we only expose the specific ones we want to be accessed by other classes, and we try to keep them to the bare minimum required.


We do this so that our classes/objects are easy to interact with.  We want to minimize confusion and eliminate the ability to use the classes in an improper way.

You may be wondering why you should care if things are public.  Afterall, public things are easy to get to, and you know what you want to get to and will ignore the rest.
But remember, current you will not be the only one working on your classes.

If your project lasts beyond a weekend, you need to think about:

  • other people – make it hard for them to misuse your classes.
  • and just as important, there’s future you.

Unless you have a perfect memory, good coding practices will help you in the future when you’re interacting with classes you wrote weeks or months ago.


Problem #2 – The Example

Let’s look at this “Wall” script now to get an idea of why proper encapsulation is so important.

using UnityEngine;

public class Wall : MonoBehaviour
    public void Update()
		if (Input.GetButtonDown("Fire1"))
	public void DamageCar(Car car)
		car.FrontTires.Tread -= 1;
		car.RearTires.Tread -= 1;

The “DamageCar” method is supposed to damage all of the wheels on the car by reducing their Tread value by 1.

Do you see what’s wrong here?

If we look back to the “Car.cs” script, “FrontTires” & “RearTires” are actually the prefabs, not the instantiated tires the car should be using.

In this case, if we execute the method, we’re not only failing to properly damage our tires, we’re actually modifying the prefab values.

This is an easy mistake to make, because our prefab fields that we we shouldn’t be interacting with aren’t properly encapsulated.

Problem #2 – How do we fix it?

If we make the “FrontTires” & “RearTiresprivate, we won’t be able to edit them in the inspector… and we want to edit them in the inspector.

Luckily, Unity developers knew this would be a need and gave us the ability to flag our private fields as editable in the inspector.


Adding the [SerializeField] attribute before private fields makes them appear in the Inspector the same way a public field does, but allows us to keep the fields properly encapsulated.

Take a look at the updated car script

using UnityEngine;

public class Car : MonoBehaviour
	private Tire _frontTires;
	private Tire _rearTires;

	public Tire FrontRightTire { get; set; }
	public Tire FrontLeftTire { get; set; }
	public Tire RearRightTire { get; set; }
	public Tire RearLeftTire { get; set; }

	private void Start()
		// Instantiate Tires
		FrontRightTire = Instantiate(_frontTires);
		FrontLeftTire = Instantiate(_frontTires);

		RearRightTire = Instantiate(_rearTires);
		RearLeftTire = Instantiate(_rearTires);

Here you see we no-longer expose the “FrontTires” and “RearTires” fields outside of our class (by marking them private).

In the inspector, we still see them available to be assigned to.

Now our problems are solved and our class is properly encapsulated!

You may also notice that the casing on them has been changed.  While this is not required to properly encapsulate your objects, it is very common practice in the C# community to denote private fields with camel case prefixed by an underscore.  If you don’t like the underscore, consider at least using camel casing for your private fields and reserve pascal casing for public properties.

Video Version

Project Download

Want the source for this project to try it out yourself? Here it is:

Continue reading >

Unity Android Deployment

By Jason Weimann / February 1, 2016

Unity Android Builds

It’s time to do a Unity Android build.  Once you complete this tutorial, you’ll be ready to build any of your projects to Android.


Grab your phone! (or tablet)

It’s time to put your game onto a phone (or tablet) so you can start showing it off to friends (or strangers if you don’t have friends).

Building your game out to an android device is actually pretty easy to do, once you have the initial setup out of the way.

Enabling Developer Options

The first thing you need to do is enable the android Developer Options

This is found in the settings of your android device, but as of android 4.2 it’s hidden by default.

To make the developer options available, go toAbout device” in your android settings.

Find the “Build number“, tap on it 7 times.

Build Number in About Device

Build Number in About Device

If you tapped correctly…. developer mode should now be available.


Go back to Settings and look for “Developer options” (for me, it’s right above About device).

Developer Options

Developer Options

Picking our options

Enable the Developer options.

Check USB debugging

Optional: Check Stay awake – You don’t have to do this, but if your phone locks it will stop your builds.

What to check in Developer Options

What to check in Developer Options

Plug it in

We’re done with phone setup, now it’s time to deal with the Unity setup.

Go ahead and plug in your phone or tablet.

Google USB Drivers

If you’re on windows, you probably need to install Googles USB drivers.  You may already have them, in which case you can skip ahead.

But if you end up with your device not being detected, make sure to follow the steps in this section.

First, download the USB driver from google here

You should get a file that looks like this

Right click on it and select “Extract All

Open the folder that’s created and find android_winusb.inf

Right click on it and select “Install

If you’re presented with this security warning, click “Open

You may be greeted with a User Account Control dialog after that, if so, just click “Yes

You should see a message saying the installation was completed successfully.

Let’s try a build

Go to your Unity editor and select File->Build Settings

Select Android from the list of platforms and click “Switch Platform

Now, make sure you have a scene selected in the Scenes In Build area.

If you don’t, you need to add one now.

To add a scene you can open it, then click “Add Open Scenes”

Leave the options at their default values and click “Build and Run

Create a folder to save the output to, then name your file.

I recommend you create a separate folder for each build platform (Android, WebGL, Standalone, etc)

Do not make it a sub-folder of your Unity project, a build is not part of your project and belongs in a separate place.

Below, you can see I have a folder at c:\builds\SwappyFish\Android and name my output file SwappyFish.apk

Click Save

An Error??

Getting list of attached devices

There are a few possibilities for what happens now.

You may have received an error saying no suitable android device was found.

If so, we need to do a bit more setup, if not, skip past this section.


Let’s Fix it


The Easy Way

Unity Select Components

Unity Select Components

When you installed Unity, there were options for different build platforms.

If you didn’t selectAndroid Build Support“, you’re probably missing the required android files.

You have 2 options here, you can re-install Unity with the Android Build Support checked (in-fact, I’d select all of the platforms there to make it easier next time  you try another target).

This could be a good opportunity to update to the latest Unity version as well.  If you want the easy way, or an update sounds good, go for that option.

The Alternative

This is a bit more involved than the easy way, but if you really don’t want to re-run the installer, this should fix the error for you.

One of the requirements for an Android build is the Java SDK.

If you haven’t already installed it (and didn’t select android build support so Unity would install it for you), you’ll need to download and install it now.

The current link to the Java SDK is here

If that stops working, just search for Java SDK on google and pick the one that looks like what’s below

The Java SDK page is not the most friendly to navigate, so just look for these 2 highlighted areas

Accept the License Agreement

Click on the download link for Windows x64

If you have a 32bit version of windows, download the Windows x86 version instead.

When your download completes, open it and you’ll be presented with the Java SDK Installer

Click Next

Keep the default settings and click Next

Now you’ll get another popup, just click Next again

While the installer will allow you to change the destination folder, I recommend against it.

The SDK should be done installing, click Close.


Build Again


Another Error? (bundle identifier)

If you got past the first part, you were probably presented with this error message.

This is telling you that you need to set the Bundle Identifier.

To set your bundle identifier, open the Player Settings under Edit->Project Settings->Player

When you click this, you’ll see PlayerSettings in the Inspector tab

If the Android option isn’t already selected, choose it by clicking on the icon that now

Your settings should look like this now, though your Product Name may be different.

Set a Company and Product name of your choice.

Expand the “Other Settings” area

You’ll see the area “Bundle Identifier” here.

Set your Bundle Identifier to something that matches the pattern.  It must start with com, then have your company name, and product name.

These’s don’t need to match exactly with your product and company, but should if possible.  Special characters are not allowed here.

My setting for this project is com.jasonweimann.SwappyFish

Once you’ve set your Bundle Identifier, save your project.

Build Again

This time, your build should actually work!

Reminder: Your phone/tablet must be UNLOCKED and plugged in for a build to deploy to it.

Deploying to Device

Deploying to Device


Well Done

If you followed the steps above, you should now have a working android build that you can show off.

Put it on a few devices and show everyone what you’ve done!

Continue reading >

How to make Unity builds – Standalone

By Jason Weimann / January 28, 2016

Standalone Builds

Alright, you’ve built a game, and it’d been great so far.

Now you might want to share your game with someone.  There are quite a few options for sharing your game, we’ll cover most of the common ones, but we’re going to start with the “Standalone” build.

Before we build though, Save your Scene!

In your editor, open the File menu and select “Build Settings…

You will be presented with a new window that looks like this

Click the “Add Open Scenes” button

Adding the currently open scene to the list of scenes to build

Adding the currently open scene to the list of scenes to build

Your scene may have a different name than mine, that’s okay, as long as it’s the currently open scene you’re working in.

Now that the scene is added, click the “Build and Run” button.

You’ll be presented with a file dialog that looks like this

Do not save here.

Select a new folder for your builds, outside of your project folder.

Here, I’ve created a folder named Builds on the C: drive.  You can place your folder wherever you like, just don’t put it in with your Unity project.

Now give it a name (mine is “SwappyFish”) and click Save

If you don’t get any errors, you should be presented with the default Unity game options screen.

IMPORTANT NOTE: We haven’t yet added a way to close the game, to get out once you hit play hold Alt and hit F4.

Click Play and give your game a try in full screen mode.  (Remember Alt-F4 to get out).

Well Done

You’ve just created your first real build of your game!

If you open Explorer (or Finder on a mac), you can see your games files in the folder you previously selected.

It should look like this on windows (and very similar on mac)

Distributing your game

To distribute your standalone build, you simply need to compress the contents of the folder into a file you can send to your friends and family.

If you already know how to zip a folder, just select the entire contents and compress them with your favorite compression tool (7-zip if my preferred one).

If you don’t know what I’m talking about… no problem, just select all of the files in the folder and right click.

Select “Send to” -> “Compressed (zipped) folder”

Compressing Standalone Build

Compressing Standalone Build

Now you have a .zip file you can share.  Go share it now, let someone see what you’ve learned!

Continue reading >

Building Flappy Bird #9 – Visuals and Beautification

By Jason Weimann / January 25, 2016

Building Flappy Bird #9 – Visuals and Beautification

In this section, we’ll do a little cleanup, and finally cover the steps to build to different devices.

The first thing we need to do is randomize our bubble heights.  While we can pop them easily, we really want some variation to make it feel more polished.

To accomplish this, we’ll use a familiar technique.  UnityEngine.Random

Open the Bubble.cs script.

We need to make two changes here.  First, Change the Reset() method to match this

void Reset()
  float randomHeight = Random.Range(-8f, -18f);
  transform.position = new Vector3(transform.position.x, randomHeight, transform.position.z);

This will give us a randomized starting height for the bubble.

If you play now, you’ll notice the bubbles are still coming at the same time.  The reason this happens is we aren’t randomizing until after the bubble has been popped and reset.  To fix this, we’ll just call reset when the game starts.

In the Bubble.cs file, add a new method named Start() that will call Reset()

Start is another built in method that we’re going to hook into.  It’s called when the scene starts or when a new GameObject is first added to the scene.

Your final Bubble.cs script should look like this

using UnityEngine;
public class Bubble : MonoBehaviour
  private float _moveSpeed = 1f;

  void Start()

  // Update is called once per frame
  void Update()
    transform.Translate(Vector3.up * Time.deltaTime * _moveSpeed);
    if (transform.position.y > 10)

  void Reset()
    float randomHeight = Random.Range(-8f, -18f);
    transform.position = new Vector3(transform.position.x, randomHeight, transform.position.z);

  void OnTriggerEnter2D(Collider2D other)
    if (OtherIsTheFish(other))
      ScoreKeeper scoreKeeper = GameObject.FindObjectOfType<ScoreKeeper>();

  bool OtherIsTheFish(Collider2D other)
    return (other.GetComponent<Fish>() != null);

Play Time

Now try playing again.

Because we call Reset when the game starts, all of the bubbles have a random initial height.

Bubbles starting at random heights

Bubbles starting at random heights


Bubble Colors

Our current bubble is pretty grey, it’s time to lighten it up a bit.

If you have access to Photoshop (there’s a free trial available), open up the bubble.png file and we’ll make an adjustment to it.


Optional – Photoshop

If you don’t have Photoshop, or just don’t want to edit the image, you can skip this section and download the modified version in the next section.

With bubble.png open, select Image->Adjustments->Levels

Move the left slider or type in the value 77

Save your file and notice how much brighter your bubble is.

Alternative – Download the Bubble

The modified bubble is available for download here

Just download it to your Art folder inside your Unity project and replace your existing bubble.


Material Changes

Now we’re going to adjust the alpha channel on our bubble material.

The alpha channel controls transparency.  We’ll be increasing the transparency (actually reducing opacity) to make our bubble look a bit better.

In your scene, select one of the bubbles, then look to the inspector.

Find the Color section and click on it

Adjusting Transparency

Adjusting Transparency

Adjust the Alpha channel to 170 and watch the bubble get a little transparent.


Background Time

Right now, our background is pretty dull.  It’s hardly a background at all, it’s really just a boring solid blue.

Let’s fix it!

Download this gradient color image

Place the GradientBackground.png file in your Art folder.

Create a new Sprite

Name your sprite “Background

Using the sprite picker, select the GradientBackground that you just downloaded

Adjust the transform values to match these

Position 0, 1.25, 0 Rotation 0, 0, 0 Scale 15, 0.4, 0

Background Transform values


Where’s my stuff??

You may be wondering where your fish and bubbles have gone…

Does your screen look something like this?

If so, don’t worry!

We just need to adjust the “Order in Layer” value on the Sprite Renderer

Order in Layer determines what order the sprites are drawn in.  Sprites that are drawn later will always cover sprites drawn before them (unless they’re transparent like our bubble).

Set “Order in Layer” to -1


Your scene view should now look like this

Good work making your game look better.

Personal Touch

Now, I want you to add a bit of your own touch to the game.

Find a new background that you really like and put it in place of the gradient.

I’d recommend you find an image on google using a search that resembles this

When you put in your own custom image, you’ll need to adjust the size of the transform to make it fit right and not be stretched out.

Here’s what my final version looks like.

Now that you’ve finished yours, post a screenshot in the comments and show everyone what you’ve done!


Up Next: Building Unity Projects – We’ll cover how to get your game built and shared with your friends on PC, Mac, Android, and in a web browser.

Continue reading >
Page 14 of 16