Thursday, 12 October 2017

Updating our C# code

Previous:KEEP IN MIND - to be successful as game developer

Updating our C# code

We need to drop boxes until all available box are done. The easiest way to do this is by using prefabs. Prefabs are reusable game object which you can use on multiple scenes, multiple times maintaining same properties.

Lets create prefab for our drop box. Create folder inside assets folder and call it Prefabs. Drag and drop our box inside this new folder. Notice the game object is highlighted in blue to show it is an instance of a prefab (object oriented programming knowledge needed to understand what an instance is - copy of game object in simple terms).




Lets now change our code to accommodate the new prefab.

Declare game object dropbox to hold our prefab: public GameObject dropbox;

Set totalboxes to 40 : int totalboxes =40;

set dropped box to 0 int boxdropped=0;


We need to check in the update function whether we have dropped all boxes. The game runs till all boxes are dropped


if ( boxdropped <= totalboxes) {

}


We need to check every time the box is destroyed, we create new one:

if (collid) {

}


Declare variable bool collid = false; On collision, set to true and on creating new one set false




void Update () {
if (collid) {
if (boxdropped <= totalboxes) {

}
collid = false;
}
}



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

}


Set collid to true inside start to star droping box


void Start () {
collid = true;
}


Create new instance of box if there is none on the scene and place at y=2.


Instantiate(dropbox, new Vector2(0,2), Quaternion.identity);


Save code and click our catch up game object in hierarchy. Check the script component and drag our prefab from prefab folder to its dropbox.



Delete the box in the hierarchy and not the prefab folder.
 


Save project and run. The boxes should drop till there are all collected.



The complete code is here:


using UnityEngine;
using System.Collections;

public class CatchBox : MonoBehaviour {
int boxescollected =0;
int totalboxes =40,boxdropped=0;
public GameObject dropbox;
bool collid = false;
// Use this for initialization
void Start () {
collid = true;
}

// Update is called once per frame
void Update () {
if (collid) {
if (boxdropped <= totalboxes) {
Instantiate(dropbox, new Vector2(0,2), Quaternion.identity);
}
collid = false;
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "box") {
boxescollected += 1;
Destroy (other.gameObject);
collid = true;
}

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


The game is stagnant. We need to move the catch up and also determine the missed box.




Next: Completing the game code

No comments:

Post a Comment