All posts in "C#"

Unity Coding Standards

Today, we’ll talk about Unity Coding Standards.  We’ll cover things to do, things to avoid, and general tips to keep your projects clean, maintainable, and standardized.

Things to avoid

I want to prefix this by saying that the thoughts in this post are guidelines and not meant to be a criticism of anyone.  These are personal preferences and things I’ve picked up from experience across a variety of different projects.

If you find that you commonly do and use some of these things, don’t be offended, just try to be conscious of the issues that can arise.  With that little disclaimer, here are some of the key things I always fight to avoid and recommend you do your best to limit.

Public Fields

I won’t go deep into this as I think I’ve already covered it here.  Just know that public fields are generally a bad idea.  They often tend to be a precursor to code that’s difficult to read and maintain.

If you need to access something publicly, make it a property with a public getter.  If you really need to set it from another class, make the setter public too, otherwise use a property that looks like this:

public string MyStringThatNeedsPublicReading { get; private set; }

Large Classes

I’ve seen far too many Unity projects with class sizes that are out of control.  Now I want to clarify that this is not something only specific to unity, I’ve seen classes over 40k lines long in some AAA game projects.  I’ve seen .cs & .js files in web apps over 20k lines long.

That of course does not make them right or acceptable.

Large classes are hard to maintain, hard to read, and a nightmare to improve or extend.  They also always violate one of the most important principals in Object Oriented Programming.  The principal of Single Responsibility.

As a general rule I try to keep an average class under 100 lines long.  Some need to be a bit longer, there are always exceptions to the rules.  Once they start approaching 300 lines though, it’s generally time to refactor.  That may at first seem a bit crazy, but it’s a whole lot easier to clean up your classes when they’re 300 lines long than when they reach 1000 or more.  So if you hit this point, start thinking about what your class is doing.

Is it handling character movement?  Is it also handling audio?  Is it dealing with collisions or physics?

Can you split these things into smaller components?  If so, you should do it right away, while it’s easy.

Large MethodsCoding Standards - too long list

Large classes are bad.  Large methods are the kiss of death.

A simple rule of thumb: if your method can’t fit on your screen, it’s too long.  An ideal method length for me is 6-10 lines.  In that size it’s generally doing one thing.  If the method grows far beyond that, it’s probably doing too much.

Some times, as in the example below, that one thing is executing other methods that complete the one bigger thing.  Make use of the Extract Method refactoring, if your method grows too long, extract the parts that are doing different things into separate methods.

Example

Take this Fire() method for example.  Without following any standards, it could easily have grown to this:

Original

protected virtual void Fire()
{
	if (_animation != null && _animation.GetClip("Fire") != null)
		_animation.Play("Fire");

	var muzzlePoint = NextMuzzlePoint();
	if (_muzzleFlashes.Length > 0)
	{
		var muzzleFlash = _muzzleFlashes[UnityEngine.Random.Range(0, _muzzleFlashes.Length)];

		if (_muzzleFlashOverridePoint != null)
			muzzlePoint = _muzzleFlashOverridePoint;

		GameObject spawnedFlash = Instantiate(muzzleFlash, muzzlePoint.position, muzzlePoint.rotation) as GameObject;
	}

	if (_fireAudioSource != null)
		_fireAudioSource.Play();

	StartCoroutine(EjectShell(0f));

	if (OnFired != null) OnFired();

	if (OnReady != null)
		OnReady();

	var clip = _animation.GetClip("Ready");
	if (clip != null)
	{
		_animation.Play("Ready");
		_isReady = false;
		StartCoroutine(BecomeReadyAfterSeconds(clip.length));
	}

	_currentAmmoInClip--;
	if (OnAmmoChanged != null)
		OnAmmoChanged(_currentAmmoInClip, _currentAmmoNotInClip);

	RaycastHit hitInfo;

	Ray ray = new Ray(muzzlePoint.position, muzzlePoint.forward);
	Debug.DrawRay(muzzlePoint.position, muzzlePoint.forward);

	if (TryHitCharacterHeads(ray))
		return;

	if (TryHitCharacterBodies(ray))
		return;

	if (OnMiss != null) OnMiss();

	if (_bulletPrefab != null)
	{
		if (_muzzleFlashOverridePoint != null)
			muzzlePoint = _muzzleFlashOverridePoint;
		Instantiate(_bulletPrefab, muzzlePoint.position, muzzlePoint.rotation);
	}
}

This method is handling firing of weapons for an actual game.  If you read over it, you’ll see it’s doing a large # of things to make weapon firing work.  You’ll also notice that it’s not the easiest thing to follow along.  As far as long methods go, this one is far from the worst, but I didn’t want to go overboard with the example.

Even so, it can be vastly improved with a few simple refactorings.  By pulling out the key components into separate methods, and naming those methods well, we can make the Fire() functionality a whole lot easier to read and maintain.

Refactored

    protected virtual void Fire()
	{
		PlayAnimation();

		var muzzlePoint = NextMuzzlePoint();
		SpawnMuzzleFlash(muzzlePoint);

		PlayFireAudioClip();
		StartCoroutine(EjectShell(0f));

		if (OnFired != null) OnFired();
		HandleWeaponReady();

		RemoveAmmo();

		if (TryHitCharacters(muzzlePoint))
			return;

		if (OnMiss != null) OnMiss();

		LaunchBulletAndTrail();
	}

With the refactored example, a new programmer just looking at the code should be able to quickly determine what’s going on.  Each part calls a method named for what it does, and each of those methods is under 5 lines long, so it’s easy to tell how they work.  Given the choice between the 2 examples, I’d recommend #2 every time, and I hope you’d agree.

CasingCasing

The last thing I want to cover in this post is casing.  I’ve noticed in many projects I come across, casing is a mess.  Occasionally, project I see have some kind of standard they’ve picked and stuck to.  Much of the time though, it’s all over the place with no consistency.

The most important part here is to be consistent.  If you go with some non-standard casing selection, at least be consistent with your non-standard choice.

What I’m going to recommend here though is a typical set of C# standards that you’ll see across most professional projects in gaming, business, and web development.

Classes

Casing: Pascal Case

public class MyClass : MonoBehaviour { }

Methods

Casing: Pascal Case (No Underscores unless it’s a Unit Test)

private void HandleWeaponReady()

Private Fields

Coding Standards - Private FieldCasing: camelCase – with optional underscore prefix

// Either
private int maxAmmo;
// OR my prefered
private int _maxAmmo;

This is one of the few areas where I feel some flexibility.  There are differing camps on the exact naming convention to be used here.

Personally, I prefer the underscore since it provides an obvious distinction between class level fields and variables defined in the scope of a method.

Either is completely acceptable though.  But when you pick one for a project, stick with it.

Public Fields

It’s a trick, there shouldn’t be any! 😉

Public Properties

Casing: Pascal Case

public int ReaminingAmmoInClip { get; private set; }

These should also be Automatic Properties whenever possible.  There’s no need for a backing field like some other languages use.

Again you should also mark the setter as private unless there’s a really good reason to set them outside the class.

 

Wrap Up

Again, this is just a short list of a few things that I think are really important and beneficial for your projects.  If you find this info useful, drop in a comment and I’ll work to expand out the list.  If you have your own recommendations and guidelines, add those as well so everyone can learn and grow.
Thanks, and happy coding!

Continue reading >
Share

Unity Baseball Bat Physics

If you’ve been following the site, you may have noticed the VR Baseball game.  While this was an interesting project, there was one part that stood out as particularly worthy of writing about.  In this article, I’ll show you how to setup physics in your own baseball, cricket, or other batting style game in Virtual Reality.  We’ll use a simple trick to make the batting feel real and fun.

Video Version

The Game

In VR Baseball, the goal is simple. A ball is pitched, you swing the bat, and if you hit, the ball goes flying.

The Problem

The first implementation of VR Baseball had a very simple batting system. There was a colider on the bat and the ball had some bounciness. Choosing a level would just adjust the bounciness factor of the ball by switching out the PhysicsMaterial on the balls Collider. It was simple, it worked, but it felt weird. The main issue was that no-matter where on the bat you hit, the ball flew the same speed.

You could hit it with the handle, it’d go flying. You could push forward with the bat and get a home run off the tip. The only thing that was taken into account was the velocity of the bat at the time.

Now in most situations, you don’t need to worry about the velocity of the exact part where your collisions happen, only the general velocity of the object it’s colliding with.  But with baseball, we have a swinging action, and we need the velocity at the end of the bat to be different from the velocity at the handle (just like real life).

The Solution

Instead of having the baseballs collide with the bat, we spawn some new objects to collide with.
The bat has a set of child objects that determine where these new objects will spawn and be at run-time.
Bat Capsules

As you can see, the BatCapsules don’t have much to them.  They’re really just a script and a transform.  There’s a collider and a mesh renderer, but those are only for debugging and visualizing, which is why they’re disabled normally (I would toggle them on when the follower seemed to be in the wrong spot, so I could verify the location I was giving them was valid).

BatCapsule Inspector

The most important part though is the “Bat Capsule” script on them.

using UnityEngine;

public class BatCapsule : MonoBehaviour
{
    [SerializeField]
	private BatCapsuleFollower _batCapsuleFollowerPrefab;

	private void SpawnBatCapsuleFollower()
	{
		var follower = Instantiate(_batCapsuleFollowerPrefab);
		follower.transform.position = transform.position;
		follower.SetFollowTarget(this);
	}

	private void Start()
	{
		SpawnBatCapsuleFollower();
	}
}

The method SpawnBatCapsuleFollower() does exactly what its name implies.  It spawns a BatCapsuleFollower, and calls a single initialization method named SetFollowTarget.  We pass “this” into SetFollowTarget() as we want the BatCapsuleFollower to follow this object which is attached to the bat.

The Start() method in this script does a single thing, it calls SpawnBatCapsuleFollower().  We do this so anyone reading the code later can tell exactly what we want to do, without needing comments.

 

using UnityEngine;

public class BatCapsuleFollower : MonoBehaviour
{
    private BatCapsule _batFollower;
	private Rigidbody _rigidbody;
	private Vector3 _velocity;

	[SerializeField]
	private float _sensitivity = 100f;

	private void Awake()
	{
		_rigidbody = GetComponent<Rigidbody>();
	}

	private void FixedUpdate()
	{
		Vector3 destination = _batFollower.transform.position;
		_rigidbody.transform.rotation = transform.rotation;

		_velocity = (destination - _rigidbody.transform.position) * _sensitivity;

		_rigidbody.velocity = _velocity;
		transform.rotation = _batFollower.transform.rotation;
	}

	public void SetFollowTarget(BatCapsule batFollower)
	{
		_batFollower = batFollower;
	}
}

The BatCapsuleFollower script is responsible for following the bat capsule…

The work for that is done in FixedUpdate().  To follow the BatCapsule, it gets the position it wants to be in, then subtracts it from the current position.  That distance is multiplied by a sensitivity value that can be adjusted in the editor.  For my game, I found a value of about 50 worked well.  It sets the rigidbody velocity to that calculated value which makes it move toward the BatCapsule.

Next it adjusts the rotation to match the BatCapsule.  If we don’t do that, it will end up sideways.

Important – Physics Layers

When setting up your BatCapsuleFollower, make sure the Layer it’s on does not collide with itself.  If you don’t, the BatCapsuleFollowers will be bouncing off each other, not doing what you want.Physics Menu

To get to the physics settings, click Assets->Project Settings->Physics

Physics Menu

In here, you need to make sure the layer you’ve chosen for your BatCapsuleFollowers (please put them on their own layer), does not collide with itself.  It should also not collide with anything other than the ball (unless there’s something else you want to hit).  You can see I’ve set mine up to do exactly that.

Physics Grid

Conclusion

With it setup like this, the BatCapsuleFollowers will move at different velocities, causing the outer most one to hit much further than the innermost.  While this could be further tuned to make a real sweet spot on the bat, I’ve found that this functionality works well enough.

Project Download

https://unity3dcollege.blob.core.windows.net/site/Downloads/VR%20Baseball%20Physics.zip

Get Some Bats

A good friend of mine made the awesome bats featured here and they’re available on the asset store.  If you wanna do some baseball stuff and support him, go grab one now 🙂

https://www.assetstore.unity3d.com/en/#!/search/page=1/sortby=popularity/query=publisher:20410

Continue reading >
Share

Unity 3D Workshop: Introduction and Building your First Game

Unity 3D Workshop: Introduction and Building your First Game

Tuesday, Apr 5, 2016, 6:00 PM

Coleman Univerity
8888 Balboa Ave San Diego, CA

18 Game Developers Went

We’re excited for our Unity Workshop tonight!  Here is some important information for the evening.1) Please bring your laptop and make sure to install Unity 5.3 beforehand2) Please also download the workshop content3) When you arrive at Coleman University, please wait at the front desk.  We will be walked back in groups to a classroom named ‘Lov…

Check out this Meetup →

I’m teaching an intro to Unity session on 4/5 with the San Diego Unity Usergroup.  If you’ve never used unity or maybe opened the editor, got lost, and quit out, this session is for you.

We’ll go over the basics of building a 3D game (no 2D stuff in this session), and build a foundation for something bigger in the future.

Bring a laptop with Unity 5.3x installed and follow along, or pair up with someone else as we go through a variety of subjects including gameplay, physics, collision, and navigation.

When you leave, you should have the base for a game and the understanding to extend it in a variety of ways.

I look forward to seeing you there!

Continue reading >
Share

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.

C++

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.

Performance

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.

Mindset

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.

Zenject

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.

Example

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"))
			SwitchToNextGameState();
	}

	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.

 

Problems

  • 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 += () =>
		{
			SwitchToNextGameState();
		};
	}

	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()
	{
		Container.Bind<IHandleInput>().ToTransient<TouchInputHandler>();
		Container.Bind<GameStateReadyToStart>().ToTransient<GameStateReadyToStart>();

		Container.Resolve<GameStateReadyToStart>();
	}
}

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 >
Share

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.

Why?

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"))
			DamageCar(FindObjectOfType<Car>());
	}
	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.

[SerializeField]

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
{
    [SerializeField]
	private Tire _frontTires;
	[SerializeField]
	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: https://unity3dcollege.blob.core.windows.net/site/Downloads/Encapsulation%20SerializeField.zip

Continue reading >
Share

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

http://developer.android.com/sdk/win-usb.html

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

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

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 >
Share

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 >
Share

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
{
  [SerializeField]
  private float _moveSpeed = 1f;

  void Start()
  {
    Reset();
  }

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

  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>();
      scoreKeeper.IncrementScore();
      Reset();
    }
  }

  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 https://drive.google.com/file/d/0B-lckWH-cZaianllZHlURFZRcVk/view?usp=sharing

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 https://drive.google.com/file/d/0B-lckWH-cZaiQVd3SnFDbmc0bXc/view?usp=sharing

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

Horray!

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

https://www.google.com/search?q=undersea+background&biw=1536&bih=748&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjrgM-HlMTKAhUClYMKHYimC8MQ_AUIBigB

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!

Sharing

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 >
Share

Building Flappy Bird #8 – UGUI – Building the UI

Welcome back!  In this section, we’ll add a scoring system.

 

The plan…

For our scoring system, we’ll use the bubble image we have in the art folder.

We’ll setup our game so that the player needs to pop bubbles for points.

To display the score, you’ll need UI components.  We’ll use the Unity3D UI system to accomplish this.

UGUI – The Unity3D GUI system

The Unity GUI system will allow us to easily draw text and graphics over our game.

Getting started with the GUI system is pretty simple, we just need to add a GUI game object.

Add a Text object by selecting GameObject->UI->Text

In your Hierarchy, you should see TWO new GameObjects.  There’s the Text that you added and a Canvas that is it’s parent.

The Canvas is the root of your UI, and all UI elements must be children of such a Canvas.

Because we didn’t already have a Canvas in our Scene, the editor automatically created one for us and added our new Text GameObject as a child.

In your game view, you should see our new Text object in the bottom left.

Let’s edit our Text object to say something more meaningful than “New Text”

With the Text GameObject selected, look at the Text component in the Inspector and notice the “Text” field.

Change it to say “Score: 0”

Anchoring

Right now, our UI component isn’t positioned correctly.  We could drag it around until it looks close, but right now it’s Anchored from the middle, so it would be at different areas depending on the screen size.  What we want for this game is to anchor the score text to the top left of the screen.  To accomplish this, we’ll use the “Anchor Presets”.

On the transform for the Text, click the Anchor tool (the red cross with a white box in the middle, the mouse is over it in the screenshot)

You’ll be presented with this dialog.

We want to select the top left point, but before you click it, notice the text at the top of the dialog.

For this UI component, we want to set the position along with the anchor, so before you click the pivot, hold the Alt key.

You should now notice your Score Text has moved to the top left corner of the screen.

Before we go too much further, let’s re-name the Text to something useful.

Change the name to “ScoreText”

Experiment

Try playing with the text component for a few minutes.

Adjust things like the font size, style, and color to get familiar with some of your options.

If you increase the font over 26, you’ll notice that it’s no-longer visible in your game view.

This is because the text is too large to fit into the component.  You can fix this by increasing the size of the text component.

Let’s Code

It’s time to hookup some code to make our score counter work.

The first thing we want to do is create a script to handle keeping score.

Create a new script named “ScoreKeeper”

Change the ScoreKeeper.cs file to look like this


using UnityEngine;
using UnityEngine.UI;

public class ScoreKeeper : MonoBehaviour
{
  private int _currentScore = 0;

  public void IncrementScore()
  {
    _currentScore++;
    Text scoreText = GetComponent<Text>();
    scoreText.text = "Score: " + _currentScore.ToString();
  } 

  void Update()
  {
    IncrementScore(); 
  } 
} 

Attach the “ScoreKeeper” script to the ScoreText GameObject

Before you hit play, look at the script and see if you can guess what it’s going to do.

 

Score Changing

Score Changing

 

Let’s inspect the different parts of this script to see what’s going on.

using UnityEngine.UI;

You’ve seen the “using” statements before.  What they do is tell the engine that we want to “use” components from that namespace.

In computing, a namespace is a set of symbols that are used to organize objects of various kinds, so that these objects may be referred to by name.

In this instance, we’re just telling Unity that we’ll be “using” UI components in our script.

private int _currentScore = 0;

Here, we’re defining a variable to hold our current score and setting it’s value to 0.


public void IncrementScore()
{
   _currentScore++;
   Text scoreText = GetComponent&amp;amp;amp;lt;Text&amp;amp;amp;gt;();
   scoreText.text = "Score: " + _currentScore.ToString();
}

The IncrementScore method does 3 things.

  • Adds one to the score using the ++ operator.  This could also be written as
    _currentScore = _currentScore + 1;
  • Gets the Text Component and assigns it to a local variable named “scoreText”
  • Sets the .text property of the “scoreText” object to have our new current score.

    ToString() gives us a text representation of a a non-text object

The last bit of code we have is the Update method.  All it’s doing is calling IncrementScore.  Because Update is called every frame, our IncrementScore method is called every frame, which in turn makes our score increase.  In this instance, the faster our game is running, the faster our score will increase.


void Update()
{
  IncrementScore();
}

The Update method is really just implemented so we can see something working.  For our game, we’ll have a more complicated scoring system, so let’s delete the Update method.

Change your ScoreKeeper script to look like this


using UnityEngine;
using UnityEngine.UI;

public class ScoreKeeper : MonoBehaviour
{
  private int _currentScore = 0;

  public void IncrementScore()
  {
    _currentScore++;
    Text scoreText = GetComponent<Text>();
    scoreText.text = "Score: " + _currentScore.ToString();
  }
}

 

Now that our code has changed, we need another way to call the IncrementScore method….

In comes the bubble

Look to your art folder in the Project View.

Drag a bubble from the Art folder into your scene.

Dragging Bubble to Scene

Dragging Bubble to Scene

Now, add a CircleCollider2D component to the newly placed bubble.

Check the IsTrigger box.

 

Let’s Code

We’ve got our bubble placed, but we really need to get some code in to make things work.

 

 

 

using UnityEngine;
public class Bubble : MonoBehaviour
{
  [SerializeField]
  private float _moveSpeed = 1f;

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

  void Reset()
  {
    transform.position = new Vector3(transform.position.x, -10, transform.position.z);
  }

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

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

Attach the bubble script to your bubble in the Hierarchy.

Now try playing and see if you can catch the bubble.

Cant catch the bubble

Cant catch the bubble

If you placed your bubble like I placed mine, it can’t be caught.

The reason for this is that we only ever change the Y position of the bubble, so it never moves past us.

Instead of adding more code to the bubble, we’ve got another trick we’ll be using.

Set the bubbles position to [2.5, -4, 0]

Now, make the bubble a child of the seaweed parent.

Bubble becoming a child of seaweed parent

Bubble becoming a child of seaweed parent

In the Inspector, hit the Apply button so that all our seaweed parents get a bubble.

Now give your game another play and enjoy your great work!

If all went well, it should look a bit like this

Popping Bubbles

Popping Bubbles

 

Next Up: We’ll randomize our bubbles, fix more bugs, and polish up our graphics (and maybe build out to a phone).

Continue reading >
Share
Page 4 of 6