Scripting with C# in Unity3D

If you've been interested in Unity3D, especially with all the talk about Windows 10 Holographic going around, you may, or may not, have had time to download Unity and see what it's all about. Well, if you've spent a great deal of time with C#, you'll probably be happy to know that you still can use C# to write scripts to use in your Unity application.

Note: For this article, I'll be using Unity version 5.4.2f2, https://unity3d.com/.

Getting a project started in Unity is straightforward, and unity has a getting started guide when creating a new project, shown here…

Unity1
Figure 1: The new project dialogue window showing 'Getting started'

You also may find a beginner's guide here on CodeGuru, in the article entitled "Universal Windows Platform Apps and Unity3D."

Creating a Script

Let's go straight in and create a C# script to be used in a scene I set up earlier. With the project tab open, showing our assets, right-click, select create, and then click C# Script.

Unity2
Figure 2: Selecting Create

Once you've created your script, and I named mine 'CodeGuruScript,' open the script an editor of your choice. I'm using Visual Studio, but MonoDevelop or a simple text editor will be more than sufficient for this article.

On opening the C# script, you'll be presented with the following piece of code…

using UnityEngine;
using System.Collections;

public class CodeGuruScript : MonoBehaviour {
   // Use this for initialization
   void Start () {

   }

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

   }
}

Now, the comments that accompany each of the empty methods in this script are quite clear. The start method will be called during initialization, and the Update method will be called once per frame. But, let's pause here and ask the question 'The initialization of what?' On their own, scripts won't do anything; we need to attach them to some object in our scene, from which everything comes to life. So, before we add some code to our script, let's attach it to one of the live objects we have already.

Looking at the hierarchy in our scene, which should have at least a Main Camera object that all scenes have automatically added on creation, we can simply drag and drop our script on the object.

Unity3
Figure 3: The objects in our scene shown on the Hierarchy list

So, when you're ready, G=go ahead and drag and drop your script from the assets window on to your Main Camera. Once you've done this, open the inspect tab, if it isn't already, and select your Main Camera. You'll see something like shown on Figure 4, showing the script attached to the object at the bottom.

Unity4
Figure 4: The properties of our Main Camera, with the attached script visible at the bottom

Attaching a script to the Main Camera can be considered a global act, and can be used as a control for your whole scene. Otherwise, scripts attached to a particular object, even ones which aren't live in the scene yet, can be considered as locally scoped to that object. The reality of this is somewhat different, because any script on any object can potentially see another object. But, given that the Main Camera will be alive during the lifetime of a scene, it's a good place for a "global" script.

Moving the Camera

So, now we have that covered; what shall we do? For the sake of this article, I'm going to move the camera back and forth using the keyboard keys W and S. Going back to our script, we want to check for these keys bring held down; so, let's turn out attention to the Update method we saw earlier because this method is called once per frame. If you want to know what the frames per second are for your game, switch to the game tab in your main view, hit play, and open the stats drop-down, as shown in Figure 5.

Unity5
Figure 5: Viewing the stats of your game during a play test

In my script, I now have the following code…

GameObject _mainCamera;

// Use this for initialization
void Start()
{
   _mainCamera = GameObject.Find("Main Camera");
}

// Update is called once per frame
void Update()
{
   if (Input.GetKey(KeyCode.W))
   {
      _mainCamera.transform.Translate(Vector3.forward * 0.1f);
   }

   if (Input.GetKey(KeyCode.S))
   {
      _mainCamera.transform.Translate(Vector3.back * 0.1f);
   }
}

During runtime, this code will keep a reference to the Main Camera by using the GameObject.Find method, which accepts a string as a parameter. This string is the name of game object we want to find. Then, all we need to do is look for the holding down of the keys we want, in this case W and S, and move the camera accordingly. If you're not a gamer, W and S are commonly associated with the action of moving forward or backwards in first person shooters, as well as other game types.

To actually move the camera, I'm using the game object's transform.Translate method, which accepts an object of type Vector3 as a parameter. Now, Vector3 is one of several such objects, and has a shortcut that allows you to indicate which direction you want to move. In the first instance, we are moving forward, so Vector3.forward is what we need. There are several such options and I recommend exploring the Unity3D development documentation at your convenience; it can be found here.

Also, note that I'm multiplying Vector3.forward by 0.1f. Declaring the value as a float is something you'll become familiar with when coding for Unity; but, the reason we are doing this is that what Vector3.forward represents might be a little too strong. Vector3.forward is in fact, shorthand for Vector3(0,0,1), with the 1 possibly being a little too much, and moving our camera too fast. Therefore, I've added the multiplier to gain a little more control over this movement. I suggest trying different values and observing the results.

At this point, I suggest running the game and having a play around. Maybe add some more keys and directions of travel to your camera. Also, I would recommend adding some more game objects to the scene so you can visibly perceive your movement around your scene.

And, that's all we have time for in this article. This is a very simple introduction to something that is very deep and broad. Unity offers a considerable amount in terms of what you can do with just moving around in your scene. If you're feeling adventurous, I suggest investigating how to make your game objects observe and respond to gravity.

If you have any questions, please find me on Twitter @GLanata.



About the Author

Gavin Lanata

Gavin has been building front-ends to software applications; desktop, web, and mobile, for several years now. Gavin often attends developer events, expanding his own knowledge in the fast paced world of IT, and lending a helping hand to developers needing a little direction navigating the world of design. Gavin has dedicated his time to the study of the many factors influencing human usage and reaction to software application. Art, design and coding name a few but certainly not the least of his tools to find the truths behind why we like and use the things we do.

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date