Tutorial: 1st-person sneak in Unity 5, part 8

It is time to create a start menu for the game. For that, we need a scene. After creating the scene, rename the scene file to “start_screen” or something like that.

(Scroll down for the links to previous parts of this tutorial.)

Add the scene to the build settings (File->Build Settings…)

Make sure that start_screen scene is scene number zero (that scene will be loaded when the game starts).

Continue reading

Advertisements

Tutorial: 1st-person sneak in Unity 5, part 5

This part adds logic for the PC and keep track of things such as health, dying. I also add functionality for invisibility (that have already partly added in Guard class).  I also add HUD using the new GUI system to show health and energy (that is used to maintain invisibility).

Previous parts:

Continue reading

Testing Public Variables in Unity

Edit 2012/12/08: A bug fix (End() did not show correct error count); change reporting: now EndCase() and End() use Debug.LogError() fuction in reporting if there were errors (otherwise Debug.Log() is used).

It is easy to forget to set a public variable of a script in Inspector and it might take some time to figure out where the problem is. The following C# program goes and checks that all public variables in a scene are set.

TestMonoBehaviorPublicVariables.cs

using System.Collections;
using System;
using System.Reflection;
using System.ComponentModel.Design;

public class TestMonoBehaviorPublicVariables : MonoBehaviour { 
    private int errCount;
    private int errCountInScript;

    void Assert(bool status, string message) {
         if(status) { 
             Debug.LogError(" Test case failed: " + message);
             errCount++;
             errCountInScript++;
         }
    }
    void EndCase(string gameObjectName, string scriptName) {
         if(errCountInScript > 0) {
		Debug.LogError(gameObjectName + " - " + scriptName + ": errors=" + errCountInScript.ToString());	
	}
	else {
		Debug.Log(gameObjectName + " - " + scriptName + ": errors=" + errCountInScript.ToString());
         }
         errCountInScript = 0;
    }

    void End(){
         if(errCount > 0) {
            Debug.LogError("Testing MonoBehavior public variable: errors=" + errCount.ToString());
         }
         else {
            Debug.Log("Testing MonoBehavior public variables: errors=" + errCount.ToString());
        }
    }

    void Start () {
         errCountInScript = 0;
         errCount = 0;
         UnityEngine.Object[] all = Resources.FindObjectsOfTypeAll(typeof(GameObject));
         foreach(GameObject go in all) {
             if(go.tag != "DontLook") { 
                 Component[] allComponents = go.GetComponentsInChildren<Component>();
                 foreach(Component c in allComponents) {
                       try{
                           RunCase(c);
                       }
                       catch(Exception e) {
                           Debug.LogException(e, go);
                       }
                 }
             } 
         }
         End();
    }

    void RunCase(Component c) {
         FieldInfo[] myField = c.GetType().GetFields();
         for(int i=0; i<myField.Length;i++) {
             string msg = String.Format("{0} - {1} ({2}): field {3} is not set", c.name, myField[i].Name, myField[i].DeclaringType, myField[i].Name);
             Assert((myField[i].GetValue(c)).ToString()=="null", msg);
         }
         EndCase(c.name, c.GetType().ToString());
    }
}

Create prefab for this script so that you can easily drop it to a scene and test all the objects. The problems are reported as errors in Console (error counts for each object and scrip are also reported as well as total number of found errors).

Drop the prefab to a scene, hit “Play” (and stop immediately), and inspect the Console.

Unity Examples

EDIT 20130525: updated links to Escape package.

I have created a small Unity package for teaching unity basics. You can download it at

To use this create new unity project (File->New Project…). Select  Toon Shading (and Image Effects if you have Pro) package(s) before creating the project.

Unzip the escape package and add it to the project (Assets->Import Package->Custom Package…).

I will add a tutorial using the prefabs and materials in the package later. Meanwhile, some introduction to the code is available in previous post (these mainly explain the principles, the current package does not match exactly to the codes):

Update1: the package is made with Unity 3.5.6.

Update2: added package that works with free version of Unity.

Simple Perception System (Unity, C#)

Here is a very simple perception C# code that I used my lecture today for Unity.

Function that can be added to the Enemy class to check if the enemy sees the player object or not (the code for other functionality can be found on the post /2011/10/29/intro-to-gameplay-programming-with-unity/). With this code, an enemy can perceive player object farther away if the player object is front and when rear on the side perseption range is more limited.There is also very simple line-of-sight checking functionality.

The features of the perception system can be controlled via class variables

public float frontRange = 10.0f;
public float frontAngle = 30.0f; // if angle between forward and los is less than this, the target is at front
public float closeRange = 2.0f;

Then the function actually handling the if enemy can see the player object or not.

public bool IsPlayerWithinPerceptionRange()  {
   RaycastHit hit;
   bool playerWithinPerceptionRange = false;
   if(Physics.Linecast(transform.position, GameAgents.GetPlayer().transform.position, out hit)) {
        if(hit.transform == GameAgents.GetPlayer().transform) {
            if(hit.distance <= closeRange) {
                 playerWithinPerceptionRange = true;
                 Debug.DrawLine(transform.position, hit.transform.position, Color.black);
            }
            else if(hit.distance <= frontRange) {
                 if(Vector3.Angle(transform.forward,hit.transform.position - transform.position) <= frontAngle) {
                     playerWithinPerceptionRange = true;
                     Debug.DrawLine(transform.position, hit.transform.position, Color.black);
                 }
            }
         }

    }
    return playerWithinPerceptionRange;
}

Intro to Unity GUI

This post contains an solutions  to my Unity programming exercises and classes I showed at the lectures. This post cover coding some basic things about using Unity GUI system.

StartScreenGUI (C#)

This class creates simple re-sizable and skinnable start screen for a game with main screen, credits screen, and confirm screen for quitting. The main screen is show in the Figure (with the textures and skin setup).

Continue reading