ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Unity C# Beginner's Cheat Sheet

Updated on October 5, 2016
beagrie profile image

Fervent writer, avid gamer, guitar lover. In between writing content for HubPages, John earns his sandwiches fixing automatic transmissions.

Unity is a powerful tool for creating video games (and other forms of entertainment), and it becomes more powerful the more you understand how to use it. Coding is potentially the biggest pitfall in this respect because requires you to understand the language rather than simply learn how to use the software.

For professional programmers who have studied and worked with code most of their lives things like remembering how a “for” loop goes isn’t a problem, but for those of us who are less well versed, it’s easy to forget some of the basics. If that’s you, this hub is here to help. Below you will find a some basic (but essential) elements and pieces of code, complete with descriptions of what they do. So the next time you’re coding in Unity and you forget how to lay out an “if” statement, load up this hub and check it as needed.

Startup

Awake() {}
OnEnable() {}
Start() {}

When a scripted object is initialised—bearing in mind that an object can be initialised at any point during the game—the above functions are run in the order listed. “Awake()” is called first upon initialisation of an object. “OnEnable()” is called next, and is also called any time an object is disabled and then re-enabled again. This is handy for placing code you want to happen any time a particular object is initialised. Finally, we have “Start()”. Practically speaking for beginners, there’s not much difference between Awake and Start other than the fact that Awake is always called first. In fact Start will not be called until all the objects in the scene have run their Awake code, so placing an initialisation code in your Awake function ensures that everything is ready to go by the time you get to your Start function.

Update

FixedUpdate() {}
Update() {}
LateUpdate() {}

These functions are where the game happens—what would traditionally be thought of as the “game loop”. These three functions are called in the order shown, over and over again until told otherwise.

“FixedUpdate()” is, as the name suggests, called at fixed intervals, which can be determined in the editor. FixedUpdate is particularly useful for placing physics-related code as it will update at regular intervals regardless of the frame rate of the game.

“Update()”, on the other hand, is called every frame. Obviously this means the actual number of times it is called can vary as the frame rate fluctuates. This function will usually carry the bulk of your non-physics game code. It will usually be the place you put player movement.

“LateUpdate()” is simply another update, but one that is called only after the Update function has run its course. If you had calculations in the Update function (for example, player movement) and you had further code that relied on those calculations (such as camera movement following the player), you would place it in the LateUpdate function so as to be sure the calculations were complete by the time your code executes.

The End

OnDisable() {}
OnDestroy() {}
OnApplicationQuit() {}

“OnDisable()” is, as you probably guessed, the counterpart to “OnEnable()”. If you disable an object during the game, this function will be called, and "OnEnable()" called once more if it is then reactivated.

“OnDestroy”, on the other hand, is called when the object is removed entirely from the game. It will run before the object is removed from the game, and can only run on active objects.

Equally as self-explanatory, “OnApplicationQuit()” is called when the player decides to exit the game entirely.

A visual breakdown of the Unity order of execution.
A visual breakdown of the Unity order of execution. | Source

During the course of the game loop, your scripted objects will be on the lookout for certain events. By placing code in the functions attached to these events, you can make things happen on cue.

Physics Triggers

OnTriggerEnter (Collider) {}
OnTriggerStay (Collider) {}
OnTriggerExit (Collider) {}
OnCollisionEnter (Collision) {}
OnCollisionStay (Collision) {}
OnCollisionExit (Collision) {}

These updates only apply to objects which have colliders attached to them. As the name suggests, the “OnTriggerEnter()” and “OnCollisionEnter()” are called upon when a collision is detected, the stay variant is called each update that two objects are touching, and the exit is called when a previously touching object is no longer touching.

The difference between trigger and collision is that a trigger is simply that, it detects the collision but does nothing other than let you know there has been one through the use of these these functions.

The collision functions, however, are between “solid” objects. To use an example, you would use “OnTriggerEnter()” to detect the player entering a trap, and you would use “OnCollisionEnter()” to detect the trap hitting the player. The “Collider” passed to the OnTrigger function, and the “Collision” passed to OnCollision, carry information about the collision, such as what object has triggered or collided with it.

Player Triggers

OnMouseUp() {}
OnMouseDown() {}
OnMouseOver() {}
OnMouseExit() {}

There are more mouse-related commands however, in the interests of brevity, and as this is a beginner’s cheat sheet, I’m stopping at these four.

The naming of these functions is clear enough, “OnMouseDown()” is called when the player presses the mouse button, “OnMouseUp()” when the player releases the mouse button. “OnMouseOver()” is called when the player’s mouse hovers over an object or GUI element, “OnMouseExit()” is called when the mouse then leaves that object.

Colliders are invisible meshes for detecting when objects touch in the game world.
Colliders are invisible meshes for detecting when objects touch in the game world. | Source

The "For" Loop

for (int i = 0; i < 10; i++) {

    // code here

}

The for loop is probably one of the most-used pieces of code in Unity, if not coding in general. Using a for loop you can not only iterate a piece of code a predesignated number of times, you can also access the number of the current loop. This makes it especially useful for looping through each instance of a thing, such as each child in a hierarchy, or each value in an array.

The “int i” is the initialising of the integer value that will be used. You could also use an already initialised value. “i < 10” tells the loop that once "i" is no longer less than 10, the loop should end. “i++” means that “i” will progress by 1 each loop. You could change this so that “i” increased by 2 each time, and the for loop would run 5 times instead of 10. If you were to put code simply printing “i” on the screen in the above for loop, you would be presented with the numbers 0 through 9.

The "If" Statement

if (condition) {
     // code here
}

The “if” statement is absolutely essential in just about any coding, not to mention being a foundation element of logic in general. The command allows you to quite simply say, “If this condition is met, then do this”.

An example would be to check your player’s health value by asking “if (playerHealth < 0)” and passing the code to kill the player to the statement. That way, every time the if statement is called it will check the playerHealth value and if it is greater than zero it will move on. If not, it will kill the player.

The Switch Statement

switch (chooseGreeting) {
 
     case 1:
     print (“Hello there!”);
     break;
 
     case 2:
     print (“Hey, how are you?”);
     break;
 
     default:
     print (“Invalid greeting choice.”);
     break;
}

The switch statement is incredibly useful when you want to act on the value of something but there can be many potential outcomes. A switch statement essentially presents a far neater way of doing what could be achieved with a whole mess of “if” statements.

Each “case” in the statement presents a different outcome depending on the value of given. “default” is there to keep the code functional should a value be passed over that does not have an associated case. The “break” command must be called at the end of each case so that Unity knows it is finished.

That’s all for this hub, it is only meant to be for those of you starting out in the wide, wonderful world of coding, after all. Be sure to comment if you’d like more of these (or if you don’t, for that matter).

© 2016 John Bullock

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.