Chapter 2. Scripting

Creating behaviors in Unity means writing code, or scripting. Scripts in Unity are written in C# (pronounced “C sharp”). C# was originally developed by Microsoft, and has since evolved to include a full, fantastic open source implementation, which Unity makes extensive use of.

Warning

We strongly recommend that you review Chapter 1 before you work through any of the recipes in this chapter!

This book isn’t going to try to give you a complete guide to programming, or a complete guide to programming in C#—that’d be a whole other book. Instead, we’ll show you how to write scripts for use in Unity, using C# as the language.

Note

There are other languages you can use to write code in Unity. For example, there are a number of bindings to other languages, and Unity supports a range of visual scripting tools that we’ll touch on in other chapters, but that are beyond the scope of this book.

If you’re interested in learning C# in a broader sense, we strongly recommend C# 7.0 in a Nutshell by Ben and Joseph Albahari (O’Reilly), as well as Head First C# by Andrew Stellman and Jennifer Greene (O’Reilly).

2.1 Adding a Script to an Object in a Unity Scene

Problem

You want to add scripts to your game objects, so that you can give them behavior using C# code.

Solution

Unity game objects are containers for components. A MonoBehaviour—named for Mono, the scripting runtime that Unity uses—is a script component. When a Mono​Be⁠haviour is attached to a game object, it participates ...

Get Unity Development Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.