[Old] Guides

/Tag:[Old] Guides

Unity for Dummies ~ 1.5: Raycasting!

We’ve established a scene with some scripts and objects to interact with. That’s great and all but our current means of communication with the scene is lacking. What we want is some kind of mouse integration. Luckily Unity has us covered. Whenever you click on the scene you can capture where that click was taken. Better still we can fire lasers out of our mouse pointer like some kind of bond villain.

Normally the lasers won’t be visible. This is because our puny human eyes can’t register the awesome might of a raycast. I’m lying, naturally, they are just invisible unless you add a line renderer (or use debug options). We won’t be doing either of these things today because we don’t need to. If it works, it works, if it doesn’t, it doesn’t.

The first thing you’ll want to do is click on Game Controllers on the left. From there open up Input Controller (alternatively if you already have it open, just go to it now). Here we’ll be adding a Raycast.

The nice thing about raycasts is that they can interact with physics objects. Our cubes have cube colliders on them which are handy boxes that will accept data from, send data to, and interact with other physics objects. That’s important since we want to click on a cube. You could take the weird way out and figure out where the mouse clicked, where the cubes are, and from there extrapolate if you clicked on them or not. But that’s not really going to help you in the future.

What you do instead is fire a laser at it. As that solves everything. I’ve done some other minor edits to this file. I’m going to post it in full below and talk about it in more detail following that.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CubeSpinner : MonoBehaviour {

public List cubeGroup = new List ();
private int correctCube;
private string lastCubePicked;

void Start () {
foreach (GameObject cubeFound in GameObject.FindGameObjectsWithTag("cubes")) {
cubeGroup.Add (cubeFound);
}
correctCube = Mathf.FloorToInt(Random.Range (1, cubeGroup.Count + 1));
}

void FixedUpdate () {
if (Input.GetButton ("Fire1")) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit _hit;
if (Physics.Raycast (ray, out _hit)) {
if (_hit.transform.tag == "cubes" && _hit.transform.name != lastCubePicked) {
foreach (GameObject cubeFound in cubeGroup) {
cubeFound.renderer.material.color = Color.white;
}
print ("You've touched cube #" + _hit.transform.name.Substring (5, 1) + "!");
GameObject.Find (_hit.transform.name).renderer.material.color = Color.green;
lastCubePicked = _hit.transform.name;
}
} else {
foreach (GameObject cubeFound in cubeGroup) {
cubeFound.renderer.material.color = Color.white;
}
}
}
}
}

At first glance it probably looks weird again. Especially given the weird formatting of my website’s code blocks. Hopefully I’ll get that worked out later. Regardless let’s move through this piece by piece for changes that I’ve made.

The first is that we’ve got some new variables!

private int correctCube;
private string lastCubePicked;

The first of these two variables is the integer for the cube you are trying to click to win. This currently has no purpose but (in our next guide) will have a point. The second variable is simply storing the last cube you clicked on. This has a performance reason that will become more clear below.

correctCube = Mathf.FloorToInt(Random.Range (1, cubeGroup.Count + 1));

Here we are storing the previously temporary variable into a permanent one!

void FixedUpdate () {

You will be using FixedUpdate for your raycasting because it will fire at the same rate as physics in Unity. For the record you probably shouldn’t use it for anything other than physics related things. For everything else, basically, just use Update ().

if (Input.GetButton ("Fire1")) {

This function looks to see if you are currently pressing the “Fire1” key. You can find all these keys and what they are assigned to under Edit, Project Settings, and then Input.

inputsMenu1

I'll cover this somewhat intimidating looking section in a later guide.

I’ll cover this somewhat intimidating looking section in a later guide.

For now just know that Fire1 is by default the same as left clicking with your mouse or pressing the screen with your finger on mobile.

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

Here we are creating a Ray, naming it ray, and then using the function Camera.main.ScreenPointToRay() to fill in the “from” and “to” requirements of a raycast.

RaycastHit _hit;

Here we are creating a variable that will store all the data from a raycast. These are known as RaycastHit. I’ve named it _hit for convenience.

if (Physics.Raycast (ray, out _hit)) {

This line says “If the raycast hit something, store the data from what it hit and run the code within the {}s.

if (_hit.transform.tag == "cubes" && _hit.transform.name != lastCubePicked) {

_hit stores a ton of helpful data. In particular we use _hit.transform.tag to find the tag we set earlier. By default it will be “untagged” but in this case we are looking for “cubes”. Additionally we want to know if the thing we are hitting is NOT the same as the last cube we clicked on. If it isn’t (that is to say, if it is a new selection) fire the code within the {}s.

foreach (GameObject cubeFound in cubeGroup) {
cubeFound.renderer.material.color = Color.white;
}

To put this simply, we are looking at each gameobject in our list from earlier and turning them all white. This clears out any previous selections. It’s messy but works.

print ("You've touched cube #" + _hit.transform.name.Substring (5, 1) + "!");

Debug message for making sure we are registering clicks. Don’t be too stressed out by the concatenation and substring stuff.

GameObject.Find (_hit.transform.name).renderer.material.color = Color.green;

For the more visual among us we’ll turn the cube we just touched green.

lastCubePicked = _hit.transform.name;

Finally we store the name of the last cube we clicked. This way we don’t infinitely loop on the same cube if we hold the mouse click down on it. I’m aware that “GetButtonDown” will only fire once but in this case it is also sketchy. I wanted 100% feedback for the user and using “GetButton” does this better.

} else {

If you clicked anywhere OTHER than a physics option we’ll fire all the code in the {}.

foreach (GameObject cubeFound in cubeGroup) {

cubeFound.renderer.material.color = Color.white;

}

This simply clears all the cubes so that the screen is back to all white with no greens.

Additionally I’ve updated the text in the scene to mirror this reality. We are now resetting the screen not by LITERALLY resetting it but instead returning all the states to default. That is to say we are making all cubes white.

The final result looks something like this.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CubeSpinner : MonoBehaviour {

/* This is where we store our public, private, static, and other kinds of variables.
* Most variable types will follow a format similar to the ones listed below.
* cubeGroup is the list of all cubes in our scene.
* correctCube is the cube you should be clicking.
* lastCubePicked is the last cube you clicked.
*/

public List cubeGroup = new List ();
private int correctCube;
private string lastCubePicked;

/* Start is a function that activates ONCE per object when the scene loads.
*/

void Start () {

/* This function is very simple. It says for each gameobject that can be found with the tag "cubes" run the function in the brackets once.
* cubeFound is the variable that stores the information found each time. You could name it anything.
* cubeFound.name would give you the name of the current GameObject that has been found following the rules I've given.
*/
foreach (GameObject cubeFound in GameObject.FindGameObjectsWithTag("cubes")) {

cubeGroup.Add (cubeFound);

}

/*
* Since this is a picker game we'll want to pick which of the cubes is the correct one.
* The easiest way to do this is to randomly pick one of them.
* */

correctCube = Mathf.FloorToInt(Random.Range (1, cubeGroup.Count + 1));

}

// We use FixedUpdate for physics related functions because we are not animals.
void FixedUpdate () {

/* This script will only happen when you have the "Fire1" key pressed.
* By default this is your left mouse button or a finger tap on mobile.
*/

if (Input.GetButton ("Fire1")) {

/* Once you've pressed down the Fire1 button we commit the following.
* First we create a new variable of type Ray with the name ray.
* That ray will use the function Camera.main.ScreenPointToRay();
* This handles the to and where requirements of a raycast.
*/

Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

//We also need a variable to store all the data for "what" the raycast hits.
RaycastHit _hit;

/* Now that we have our ray we then ask if that ray has hit anything.
* If the Raycast hit anything physical we'll trigger the script in the {}.
*/

if (Physics.Raycast (ray, out _hit)) {

//Is the thing we hit one of our cubes? If yes tell us which cube it was.
if (_hit.transform.tag == "cubes" && _hit.transform.name != lastCubePicked) {

/* This ultimately isn't perfectly efficient but we'll be updating it in our next tutorial.
* All this does is go through the cubes and make them all white.
* That way there is only ever one green cube at any one time.
*/
foreach (GameObject cubeFound in cubeGroup) {

cubeFound.renderer.material.color = Color.white;

}

/* Substrings are just used for truncating text.
* I'm telling it to only use 1 character after the 5th letter in the objects name.
*/
print ("You've touched cube #" + _hit.transform.name.Substring (5, 1) + "!");

GameObject.Find (_hit.transform.name).renderer.material.color = Color.green;

lastCubePicked = _hit.transform.name;
}

} else {

/* This ultimately isn't perfectly efficient but we'll be updating it in our next tutorial.
* All this does is go through the cubes and make them all white.
* That way there is only ever one green cube at any one time.
*/
foreach (GameObject cubeFound in cubeGroup) {

cubeFound.renderer.material.color = Color.white;

}
}
}
}
}

And that’s that! A new version of what you should have is shown below. I’m not sure what we’ll cover next. Likely win/lose conditions of some kind since there currently aren’t any.

Previously in Unity Guides:

Unity for Dummies ~ 1.4: foreach loops and lists!
Unity for Dummies ~ 1.3: Tags and C# Introduction
Unity for Dummies ~ 1.2: Prefabs and Children
Unity for Dummies ~ 1.1: Project Creation

By | 2015-01-02T20:16:39+00:00 January 2nd, 2015|Journal|Comments Off on Unity for Dummies ~ 1.5: Raycasting!

Unity for Dummies ~ 1.4: foreach loops and lists!

When last we spoke you were working on the Input Controller script. Now we’ll move on over to the Cube Spinner script. At least for now it won’t ACTUALLY be spinning the cube but eventually it will be. For now it will instead be recoloring the cube. The reason for that is we want a nice simple debug to show us that our list and foreach loops are proper. But, you might be asking, what the hell are those two things I just said?

I’m glad you asked! First I’ll post the entire script.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CubeSpinner : MonoBehaviour {
public List cubeGroup = new List ();
void Start () {
foreach (GameObject cubeFound in GameObject.FindGameObjectsWithTag("cubes")) {
cubeGroup.Add (cubeFound);
}
int cubeToPick = Mathf.FloorToInt(Random.Range (1, cubeGroup.Count + 1));
print (cubeToPick);
GameObject.Find ("cubey" + cubeToPick.ToString ()).renderer.material.color = Color.red;
}
}

Chances are that what you see before you looks to be just jibberish. If that is the case I totally relate and the first time I looked at scripts I had no damn clue what they were doing. We’ll go over this line by line and I’ll explain how each thing works to the best of my abilities. What I say might be wrong in terms of terminology but, as mentioned previously, I should at least be internally consistent.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

These are the three script libraries we’ll be pulling from. We are using a bit from the first, a bit from the second, and at least one thing from the last. You’ll notice that your default script already has the first too. So just add “using System.Collections.Generic;” beneath those.

Spelling is important, capitalization is important, and don’t forget that semicolon!

public List cubeGroup = new List ();

This is our list. A list is basically just an array that has been given a specific type that it will allow inside of it. Think of lists (or arrays) as labeled shelves. What we’ll be putting onto them are basically boxes or packages. In the case of a list we say “I want to put ONLY this kind of box or package on these shelves. If I put anything else, scold me.”

Our shelf will be explicitly filled with “GameObjects” which is a unity type. Every object in your scene (as far as I have noticed) is a GameObject.

List<> is the format with whatever you put inside the <> being the only thing you can add to the list.

Next we name the list. I’ve named mine cubeGroup (note the lower case c) because that’s what it will be. A list of all the cubes in our scene.

We want to give this list a value of some kind. Otherwise it will be a “null value”. Generally speaking if you don’t initialize variables (that is, tell the program what to expect from them) they’ll end up being null. When things are null it causes all kinds of problems. Null is simply something that has literally no value. Not even 0. It’s value does not exist nor can it be tangibly defined by our feeble minds. Weakly we call it “null”.

Following the = sign we tell the program what we want to initialize this variable with. A new List sounds nice! That list can only be filled with GameObjects. The brackets to the right of it are because this is a function. we are passing nothing through the function so we keep it empty. Sometimes you can do this, sometimes you can’t, you’ll learn when and when not mostly by trial and error. Finally ending it with a semicolon.

foreach (GameObject cubeFound in GameObject.FindGameObjectsWithTag("cubes")) {
cubeGroup.Add (cubeFound);
}

Inside the Start () function we have our first action! When I first started coding I was using all kinds of loops to accomplish this kind of task. While loops (which I’ll discuss some other time) and for loops (again later). Then I came across “foreach” and it made me sooooo happy.

Previously we mentioned that scripts are really asking “Is the things inside the () true? If so do something.” What a foreach does is say “Each time the things in the () is true, do the things inside the {}.

From left to right we are saying “For each time that a GameObject, which we’ll define as cubeFound, is found in the function GameObject.FindGameObjectsWithTag(“cubes”) we want to run the function cubeGroup.Add (cubeFound).”

That sounds like a mouthful and I suppose it is. The things to the left of the “in” are where you assign types and a variable. The type of thing we are looking for is GameObjects. So we say as much. Then we tell the game to assign whatever we find to a variable. We call that variable cubeFound for convenience. Since whatever we find will be a cube. We’ve found a cube, cubeFound. I’m not very fond of clever variable naming. Blunt is best.

Following the “in” we have the function that will be run to give us our list of “truths”.

GameObject.FindGameObjectsWithTag() is a unity function. What it does is use the string you put inside of it and find the Object OR Objects with that same tag. Because I’ve used the plural “Objects” it will be finding all the in scene objects with that tag. In this case “cubes”, which we set yesterday on our prefabs.

Each time it finds a cube it will assign that cubes GameObject data to the variable cubeFound.

Then it runs the list function Add. Which literally just adds something to a list. Adding that object we found to the list.

It repeats this once for each time it found a “truth”. In this case that will be 5 times.

After that we move onto our debug.

int cubeToPick = Mathf.FloorToInt(Random.Range (1, cubeGroup.Count + 1));

This one looks a bit more nasty than it is.

We are creating a temporary variable (since we don’t need it for long). That variable will be of type “int” which is short for “integer (whole numbers)”. We name that integer “cubeToPick” because that’s exactly what we are using it for.

We tell the program that this variable is equal to “Mathf.FloorToInt(Random.Range (1, cubeGroup.Count + 1));”.

Lets break this down into its constituent parts.

Mathf.FloorToInt()

This is a simple math function that takes whatever value you put into it and “floors” it to the nearest integer. Flooring something is just nerd speak for Rounding Down.

Random.Range()

This is another simple function that picks a number between a minimum value and a maximum value. Note that this is a “float” which almost always is not a whole number (because there are more non-whole numbers in most operations than whole ones). Keep in mind between is taken literally. As far as I can tell if you do Random.Range(1,5) two values you’ll never see are 1 or 5 because neither is “between” 1 and 5.

Anywho, What is the range we’ve picked?

(1, cubeGroup.Count + 1)

Our lowest value is “1” because our first cube is named “cubey1”. If you haven’t put integers following the names of your 5 cubes I recommend doing that now. Sequentially from 1 to 5. Technically you could make it 0 to 4 but I’ve named mine 1 to 5 and am just sticking with that.

On the right side of the comma we’ve got cubeGroup.Count + 1. cubeGroup.Count is the “size” of our list. That is, how many boxes are on the shelf. In this case there are 5 boxes. Keep in mind that arrays start at 0. That won’t matter here but at some point in the future we’ll talk about “off by 1” errors. These are some of the most common errors in coding. What DOES matter here is that, as I mentioned, we need to include all values in our group so we can’t stop at 5 for the upper limit. We need to go one higher. That way the random range is picking a number between 1 and 6 and rounding down. This means 1.00000000000000000000000000000000000001~ to 5.9999999999999999999999999999999999999999999999~ rounding down to the nearest integer. This gives us 5 possible outcomes.

1,2,3,4 and 5.

Which is what we want!

I’ve edited the last couple bits like 12 times. So if I failed on my copy pasting please point it out in comments and I’ll fix it.

ANYWAYS.

print (cubeToPick);

This is just for debugging. It will print into your debug window during testing.

debugWindow

See!

Finally we want to change the color of the one that we’ve picked for making sure this works visually. Not everyone likes reading text.

Which…I realize…if you’ve made it this far in my tutorial you might not be the target audience for the next line.

GameObject.Find ("cubey" + cubeToPick.ToString ()).renderer.material.color = Color.red;

Again we pull from the GameObject class this time using the “Find” function.

We’ll be doing something called concatenating. That’s fancy talk for “mooshing two things together.”

concatenate

You shut up dictionary. I don’t need none of your fancy book learnin’.

The two things we’ll be mooshing together are the word “cubey” and the integer that we got above. The problem is that integers and strings don’t moosh. Its like trying to combine vinegar and oil. Sure on bread its delicious and you want it right now omg, that would be so good in my mouth.

k

But in coding trying to combine two unlike objects usually leads to incredibly hard crashes. Because of this we’ll take our integer and turn it into a string.

How do you do that?

cubeToPick.ToString ()

…Oh. That was fairly straightforward.

Now that we have “cubey” + cubeToPick.ToString() finished we’ll shove it inside the () of Find.

At this point the script will only see 1 of 5 words. “cubey1, cubey2, cubey3, cubey4, or cubey5” which is great since that’s the name of all 5 of our cubes.

We then say we want to find the renderer of this object. Furthermore we want to find the material on that renderer. Then, because we are needy, we want to find the color.

Once it digs down deep and finds the color we say “Great bro, I love it. Except I want it to be red now.”

Unity lets out a deep sigh and does that for you.

Conveniently since we aren’t setting some permanent variable for this operation the cubes will only stay red for as long as you tell them to. I wasn’t actually expecting this but anything that saves me time and energy is great. Once you hit save, and presuming you didn’t typo, you can go into the game window and test it out. Hit that blue play button at the top and then mash on the R key.

EDIT: The day after I wrote this I remembered that the reason the red cube stops being red is because we are resetting the entire scene. Well…now you know.

Your red cube should dance all over the place, never content with the cube it previously was a member of.

Our debugging is done. That means for our next project we’ll be adding in the “picker” function. This will involve one of my other favorite toys: Raycasting.

As always, ask any questions you might have and I’ll answer them to the best of my abilities.

Stay tuned I suppose.

Previously in Unity Guides:

Unity for Dummies ~ 1.3: Tags and C# Introduction
Unity for Dummies ~ 1.2: Prefabs and Children
Unity for Dummies ~ 1.1: Project Creation

By | 2015-01-02T20:15:45+00:00 December 30th, 2014|Journal|1 Comment

Unity for Dummies ~ 1.3: Tags and C# Introduction

We’ve got a project. We’ve got lighting. We’ve now got prefabs of our cubes and all the goodies that come with them. Now it is time to start building scripts. Presuming that you followed my lead and made an empty object called “Game Controller” click on that now. You should see nothing but a tranform on the right. Where that transform is literally doesn’t matter. Mine is at somewhere weird so I’m going to reset it by right clicking on the bold word “Transform” and then clicking “Reset”.

reset

The eagle eyed among you are noticing that I’ve got two other things attached to my game controller. We’ll get into those shortly. First lets take care of that tag that says “Untagged” just above the word reset in my image. To fix this we’ll click on Untagged. By default unity has a tag for GameController already. So just select that and we’ve tagged it! Next you’ll want to add a tag for the cube prefab. Click on the cube in your Prefab folder, then click on the Tag area.

addingTags

You’ll notice I have a tag called “cubes” but you do not. Rectify this by clicking Add Tag… and then adding cubes cubes to Element 0.

tagsInspector

After you do this click on the cube prefab again and select your new tag from the drop down list like I have. Now that we’ve done this we’ve got two handy tags for the only two objects we’ll likely be interacting with in this build. Next we’ll move onto C# because that’s probably why you are really here. You don’t want my help navigating Unity. You want help making cool shit happen with words.

I can oblige.

Click on your Game Controllers object and then click “Add Component” on the right of the screen in the inspector. From there select new script. Name the script “InputController” (caps is always important), set the Language to CSharp, and then click “Create and Add”.

newScript

Mine is throwing an error because I already have this script. Yours will not.

Repeat this process and make another script called “CubeSpinner”.

Once you’ve done this double click on the script file for InputController. Found here:

clickScriptHere

Once you double click on this unity should open something called MonoDevelop. This is where all our fun time will begin.

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
}

Looks kind of daunting at first glance. At least I thought so a few months ago. We’ll cover this from top to bottom and then move onto adding cool stuff to it. Note that I might not use correct terminology but I’ll be at least internally consistent with my explanation.

using UnityEngine;
using System.Collections;

These are reference classes for your script. What these do for you is add in all of the unity functions that you’ll be using and then some additional system functions. If you deleted either of these you’d be in for a very bad time. We’ll be adding an additional line to this once we get to scripting but for most purposes these are fine.

A “class” is just a fancy name for scripts or bundles of scripts. UnityEngine is, at the end of the day, just a ton of scripts all jumbled together. For example:

public class Example : MonoBehaviour {

In this example we have a class (script) called Example. MonoBehavior is the type of script. This line looks more like Javascript than it does C# so you won’t be using this format with the colon again. This class is a “public” class which means that you can reference it in other scripts (which we’ll be doing shortly).

// Use this for initialization
void Start () {

}

This is a standard function for Unity. Every object has it upon creation but you can choose to remove it or leave it empty. Anything you put in this function will fire a single time when the object is added to a scene.

// Update is called once per frame
void Update () {

}

This is another standard function that is activated once every single frame. That means if you are running at 30 FPS it’ll activate 30 times in a single second. 60 FPS? Twice that! There are other functions like FixedUpdate and LateUpdate that we’ll be using in future projects but for now Update is fine. If this seems daunting don’t worry about it too much. We’ll take it slow and if you happen to have questions feel free to post them in the comments below. I’ll answer them to the best of my abilities.

What makes up a C# script? Generally speaking we have the availability of the function(s). Public, Private, Static. Probably some others I’m not aware of. I almost never use anything but private and public. A private function can be referenced from inside the script it is a part of. A Public function can be referenced by any script in the project. The reason you might want to use private scripts sometimes is that you might not want them to be reached by other scripts. The more private stuff you have the less debugging you’ll have to do later.

Crap I forgot what I was talking about. Well anyways lets get into the meat of it. Did I say meat yet? I cooked a lot of meat today and it is kind of on my mind. Tasty meat.

The first thing we want to add to this “game” of ours is the ability to really quickly reset the scene. I’m sure there are many ways to do this but I’ve got a few clever tricks to make a really fast (and effective) reset method.

Open up InputController and make it look like this:

using UnityEngine;
using System.Collections;

public class InputController : MonoBehaviour {

public KeyCode resetButton;

void Update () {

if (Input.GetKeyDown (resetButton)) {

Application.LoadLevel(0);

}

}
}

Now I’ll explain the code I’ve added. I’m copying and pasting the comments I wrote in the file for my own convenience. If you ever want to write longhand comments /* */ is the way you do it. As shown below.

/* We want to set the “button” we’ll be pressing in the Inspector. Because who really wants to be coming into this file all the time?
* To do that we create a “public” variable. We set its type to KeyCode and then its name to resetButton.
* Capitalization is important here! This is called camel case. You always keep the first letter of a variable lowercase.
* Then capitalize the first letter of each word following the first word.
* This way you can immediately tell if a word you are referencing is a script or a variable.
* ResetButtons…clearly a script because all caps. resetButton…clearly a variable because of the lowercase.
*/

public KeyCode resetButton;

/* We’ve deleted the start function because we don’t need it.
* Leaving us with Update. This is checked in every frame which is good since sometimes people won’t be pressing a button.
* But sometimes they will be!
*/

/* Did the person press the button we set as reset? If yes, do what is inside of the { } brackets.
* Whenever you see if (something) { } that’s asking simply “Is the stuff inside the () true?
* If yes, do this stuff, else don’t.
* We’ll get into more complicated scripts later but this interpretation is simplest.
*/

if (Input.GetKeyDown (resetButton)) {

/* Application.LoadLevel() is a function that loads a level by numeral. We could do this by name too I’m sure but for now that’s moot.
* The scene we are working on is scene 0. Because all indexes/arrays begin at 0.
* So Application.LoadLevel(0) must, by definition, load the scene we are in.
* This effectivelly resets the scene.
*/

Application.LoadLevel(0);

Which all comes together to look like this:

InputControllerScript

Ironically dozens of lines of comments for what amounts to a few lines of code. But I’m all about commenting to keep things clear…or unclear. I’m only being this verbose because I want people to know how things work as best I can.

Now that we have this all done go back into the inspector.

reset

See that handy dandy Reset Button prompt? Click the button on the right and select any key you wish. I picked R because well…reset. Ultimately the letter you pick is up to you.

Congratulations! You’ve just written your first C# script. Well kinda…I mean you copied mine. But if you want you can delete the copy paste and write the entire thing by hand yourself. Each day I’m going to cover one (or two) different C# functions or tricks you can use. Tomorrow we’ll be diving into the second script which we’ll be using to change the color of our cubes. We’ll be using trickier C# there but I’ll try to explain it so that you know how to use it. Ironically that script is also only a few lines long to accomplish what we need. Largely because it uses a foreach statement. They are, if I’ve not mentioned them yet, one of the coolest things. They will reduce your work load by a factor of a batrillion. I think that’s accurate.

It must be.

Previously in Unity Guides:

Unity for Dummies ~ 1.2: Prefabs and Children
Unity for Dummies ~ 1.1: Project Creation

By | 2014-12-29T23:53:39+00:00 December 29th, 2014|Journal|2 Comments

Unity for Dummies ~ 1.2: Prefabs and Children

We’ve got a project and lighting doing absolutely nothing of value. Next we should add some content. As with the project section in the bottom left (where you Assets are stored) we should make use of folders in the Hierarchy section. This is done by “creating empty” objects. You can find this by clicking the Create button and then clicking “Create Empty” at the top.

createEmpty

I recommend creating three of these. Name one “Cubes”, the next “Game Controllers”, and the last “User Interface”. If you wish you can organize them as I have mine listed but ultimately that matters the least in this project.

heirarchyList

Now that we’ve got our Camera, light, and three empty objects we should start populating them. Click on “Cubes” and then click on create. On the drop down menu you should see “3D Object” and “Cube”. This is what we want so click on that. This should add it to your empty object called “Cubes” as something known as a “Child”. When an object is created it is given an “origin” in the game. Generally this origin is 0,0,0 in relation to the entire scene. This means that new objects exist at the very center of your screen by default. A “Child” sets its origin to the origin of its “Parent”. So if the Parent object was at the coordinates 1,2,3. The child’s 0,0,0 would put it at 1,2,3. Similarly if the parent was in that same position and the child was 1,1,1 its position in the scene would be at 2,3,4.

This is because it would be 1 up, 1 out, and 1 to the side of the origin of the parent. The position 1,1,1 in this example is known as “Local Space” which is the location of the child in relation to what it cares about (It’s parent, awwww). The position of 2,3,4 would be its “World Space” which is its location in the scene. We’ll cover why these are important at a later date. Hopefully I’ve explained them correctly. As always be sure to double check my information with Unity. But this understanding has worked for me thus far.

Now that you have a child cube beneath your “Cubes” section we should get to work on it. Click on the cube and you should see an object roughly similar to this.

cubey

You are probably missing the “Rigidbody” which we might not even need. I’ve only added it currently because I might use it in the future. For now you can ignore that and if we find we don’t need it I’ll remove it from my project. What you DO have is the Transform, the Mesh Filter, the Box Collider, the Mesh Renderer, and Possibly the Shader. Your cube is probably very boring right about now.

lameCube

What you’ll want to do first is change the Scale of your Cube. I recommend doubling everything. This will put it at the size I’m using. But still its a boring cube that, because we are in 2D, looks like a square. That last problem is fine, the cube looking boring is not.

Click on “Materials” in your Assets section at the bottom left of the screen. Then in the window to the right of it right click, select “Create”, and then select “Material”.

createMaterials

Name it “cubey” or whatever you want. The name isn’t all that important for this project. It should look like this.

materialScreen

For the purposes of this relatively simple guide I suggest that you change the dropdown to the right of the word “Shader” from “Diffuse” to “Decal”. Then click on the “Select” button beneath “None (Texture)” and go find any art on your computer that you’d like to use. I’ve obviously used the “Continue” art because I find it cute but you can use anything. A kitten, a badger, whatever.

Once that is done it should look roughly like this.

materialScreenUpdated

Next just click on the material in the Asset section and drag it onto the Cube you made earlier. This should add it to the cube! You may notice that your image is upside down. If this is the case put “90” into the Y value of Rotation on your cube object (just like in my image above). This is found in the Transform section. That should correct the image so that it is right side up. If it doesn’t screw around with either your image or the rotation of your cube. Ultimately it won’t matter how the cube is rotated for this tutorial.

Now that THIS is done your project should look similar to mine except that you only have ONE cube. This is just not acceptable! So what I want you to do is click the “Prefab” folder on your Assets window. Then click on the name of the cube that you made in the Hierarchy and drag it from up there into the big window to the right of “Prefabs”.

dragAndDrop

Congratulations! You’ve just created your first Prefab!

So…what is a Prefab? To put it simply this is an object that you can easily clone in the scene. Each clone that you add to the scene of this object will follow all of the rules and changes that are made to this object. That’s important because sometimes you want to have say…50 of something but you don’t want to have to edit 50 different objects when you realize some small thing about them is wrong.

Now that you have your prefab you can drag a copy of it up into that Cubes section. Be sure to rename the cubes so that they don’t have the same name (for simplicity). Additionally if you already have a prefab in the scene (Prefabs are blue named objects, btw) you can right click on them and then click “Duplicate” to quickly make a duplicate! Now if you add (or remove) modules from the prefab in the Assets folder it will add or remove them from ALL the clones in the scene! Extremely convenient!

Make 5 cubes and position them any way you want at all in the scene. Once you’ve done this you are done with today’s tutorial! Tomorrow we’ll talk about Tags and an introduction into C# where I’ll teach you about loops and the basics of this magical coding language.

Previously in Unity Guides:

Unity for Dummies ~ 1.1: Project Creation

By | 2014-12-29T23:54:25+00:00 December 27th, 2014|Journal|2 Comments

Unity for Dummies ~ 1.1: Project Creation

I hope everyone had a wonderful Christmas or whatever ya’ll are calling it these days. For my belated gift to everyone I’m going to start teaching folks how to use unity. Our first project will be a small 2D game. Extremely simple because I want to teach at the most basic level. After we complete this game we’ll move onto a simple 3D game. Then if things are going well an intermediate 2D, intermediate 3D, and finally advanced games of both “Ds”. Possibly even a game that uses both 2D and 3D.

But we are getting ahead of ourselves. First we need to finish the first tutorial. So today we’ll be installing unity and then creating our scene. In some cases I might make short tutorial videos to walk people through things. That won’t be happening today at the very least but if there is something I think is unclear I’ll use video to clarify. Otherwise it’ll be screenshots and succinct information. As succinct as I can manage…which is to say…not succinct really. Note that this first guide won’t be teaching you any C#. It’s merely to get your scene ready for all the fun that is to come.

I’m not one to write guides very often but I suppose we’ll start from the beginning and end with our first goal. You won’t be reaching that goal with this edition of the guide but you probably will hit it by the next update. The first thing you’ll want to do is create a project. Well…the first thing you want to do is download and install unity. But I am assuming you figured that out at least.

Call your project anything you want. Also make sure to change that “Setup Defaults” to 2D because by default it will say 3D. This isn’t a really big deal but it at least gets you started properly. I won’t be using any of the prebuilt packs they have but in the future if you want to use any of them you totally can.

creatingproject

Now you’ll see the UI for Unity in all its initial daunting glory.

mainscreen

The first thing you’ll want to do to start this project is get some folders going. The Assets folder in the bottom left of your screen is going to be the home to everything you’ll be using on this little adventure. Just click on Assets and then on Create and select “Folder”. I’d suggest making yours look a bit like this to follow along with me better.

AssetsFolder

Once this is done we’ll move up to the top left of our screen. This is your scene Hierarchy section. This is where all the actual “Game stuff” will be. We basically pull things from the Assets and move them here (or vice versa as you’ll see soon). You can safely ignore the camera for now. It is already setup for our project. If you want to play with it you can. Just hit ctrl+z if you break anything to undo what you’ve done.

Also at any time feel free to save.

The first thing we’ll add is a Directional light. Just click “Create” under the Hierarchy section and select Directional Light. This should add one to your Hierarchy just beneath your Main Camera. Feel free to move it around if you want. I put mine over a bit out of the way. Here are my specs if you want to replicate them. We’ll talk more about lighting later (as that isn’t my forte).

DirectionalLight

If you want to move the light around yourself you can do so by selecting the cross button on the top left of your screen. Once you’ve clicked that you can select the Directional light and drag it around in the Scene view. Just note that because you don’t have any objects in the scene you won’t see any impact by the light yet. Feel free to add a simple object to the scene if you want to experiment with the light early.

MovingThings

Ignore the rest of the things under the Hierarchy section. I’ll talk about those more later. But for now feel free to move the light around. It should have minimal impact in what we’ll be doing in the next few guides. But now we’ve got a scene, a project, some assets folders, and a light in the scene. If you hit play it should be very boring and very blue. But after the next guide we’ll have something similar to the following. Note that it isn’t all that overwhelming but that’s because we’ll be doing some simple (but informative) tricks to get us going.

Not very pretty but as of the next post you’ll have built your own (with your own images) and they’ll dynamically color. Following that we’ll turn this into an honest to goodness picker where people have to pick the correct one to move on. Maybe we’ll do some simple animation to make it even more amusing. But that remains to be seen.

By | 2014-12-27T22:34:28+00:00 December 27th, 2014|Journal|2 Comments