Book Image

Learning C# by Developing Games with Unity 2019. - Fourth Edition

By : Harrison Ferrone
Book Image

Learning C# by Developing Games with Unity 2019. - Fourth Edition

By: Harrison Ferrone

Overview of this book

Learning to program in today’s technical landscape can be a daunting task, especially when faced with the sheer number of languages you have to choose from. Luckily, Learning C# with Unity 2019 removes the guesswork and starts you off on the path to becoming a confident, and competent, programmer using game development with Unity. You’ll start off small by learning the building blocks of programming, from variables, methods, and conditional statements to classes and object-oriented systems. After you have the basics under your belt you’ll explore the Unity interface, creating C# scripts, and translating your newfound knowledge into simple game mechanics. Throughout this journey, you’ll get hands-on experience with programming best practices and macro-level topics such as manager classes and flexible application architecture. By the end of the book, you’ll be familiar with intermediate C# topics like generics, delegates, and events, setting you up to take on projects of your own.
Table of Contents (20 chapters)
Free Chapter
Section 1: Programming Foundations and C#
Section 2: Scripting Game Mechanics in Unity
Section 3: Leveling Up Your C# Code

Camera follow

The easiest way to get one GameObject to follow another is to make one of them a child of the other. However, this approach means that any kind of movement or rotation that happens to the player capsule also affects the camera, which is something we don't necessarily want. Luckily, we can easily set the position and rotation of the camera relative to the capsule with methods from the Transform class.

Time for action – Scripting camera behavior

Since we want the camera behavior to be entirely separate from how the player moves, we'll be controlling where the camera is positioned relative to a target we can set from the Inspector:

  1. Create a new C# script in the Scripts folder, name it CameraBehavior, and drag it onto the Main Camera.
  1. Add the following code and save it:
 public class CameraBehavior : MonoBehaviour 
// 1
public Vector3 camOffset = new Vector3(0, 1.2,...