Friday, 11 November 2016

Complete C# code



Previous: Turning Pseudo code into C# code



using UnityEngine;
using System.Collections;

public class CatchBox : MonoBehaviour {
    int boxescollected =0;
    int totalboxes =0;
    // Use this for initialization
    void Start () {

    }

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

    }
}

  
Lets add new method to check collision:

void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "box") {
            boxescollected += 1;
            Destroy (other.gameObject);
        }

    }


Since the code is attached to "catch up", it detects collision between it and other game objects. We check if the object has tag "box" and add
boxescollected. We then destroy the box.

We need to display our boxes. We use OnGUI method 

void OnGUI()
    {
        GUI.Label (new Rect (10,10, 300, 50), "Boxes collected: " + boxescollected);
    } 


Save the code. 

Below is the complete code for our game: 

using UnityEngine;
using System.Collections;

public class CatchBox : MonoBehaviour {
    int boxescollected =0;
    int totalboxes =0;
    // Use this for initialization
    void Start () {

    }

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

    }
    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "box") {
            boxescollected += 1;
            Destroy (other.gameObject);
        }

    }
    void OnGUI()
    {
        GUI.Label (new Rect (10,10, 300, 50), "Boxes collected: " + boxescollected);
    }



Run the game


 




This is the most basic games.

Next: Advancing further 

No comments:

Post a Comment