Creating the Script

Now, we are good to go to start writing some scripts. This is the first script of this book, and since it's a book with examples, we will jump straight into one, and learn how to code by deconstructing what we are doing. Don't be scared if it is not clear to you at the beginning, because it might be hard if it's the first time you see the code. Don't give up; being able to code is worth the effort.

To create a Script, we need to create a new folder, called Scripts, as shown in the following screenshot:

  1. Inside the folder, right-click and then Create|C# Script (Alternatively using the top-menu Assets|Create|C# Script )
  2. Rename the script to PlayerController so we will always know later what the script is supposed to do
  3. The script can be used as a component, meaning that it can be attached to a GameObject
As we have seen in the previous chapter, not all the scripts are components. For instance, Editor scripts are not components, and in general, every script that does not derive from MonoBehavior is not a component.

So, let's drag it onto our character GameObject, and it will appear in the Inspector, like the following screenshot:

If you double-click the Script component, an editor will open depending on your preferences in the settings. The default is MonoDevelop, but also Visual Studio (www.visualstudio.com) is excellent.

Once opened, this is how the script looks:

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

public class PlayerController : MonoBehaviour {

// Use this for initialization
void Start () {

}

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

}
}

At the beginning, there are three lines that allow us to use libraries. At this stage, we won't touch them.

Then, there is the class definition, in this case, named PlayerController. Inside it, there are two functions: Start() and Update(). The first is called every time this script starts, whereas the second is called at every frame. You can explore the whole execution order of the different functions and scripts by following this link: https://docs.unity3d.com/Manual/ExecutionOrder.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset