Thursday, 10 November 2016

Turning Pseudo code into C# code

Previous: Score display in pseudocode

It is now time to turn our pseudocode into C# code and display our score

initialize boxcollected to zero
initialize totalboxes to zero

drop box
if collected 
  increase boxcollected by one
print boxcollected
end if
increase totalboxes by one
print totalboxes

In unity editor, inside assets folder, create a folder (from project menu, create -> folder) and name it Scripts. inside this folder, add C# script from project menu, create ->C# Script and name it CatchBox. 

Double click our new script to open. It opens with the default code.

We begin by declaring variable to store boxes collected
int boxescollected =0;

Then declare variable to store total boxes:
 int totalboxes =0; 

Every time a box is added to game, we add totalboxes: This will be added inside update method

totalboxes +=1;
We will use colliders added to the boxes to determine when the boxes collide. This denotes the box was collected. Every time the two boxes collide, we add boxescollected. We add a new method to detect collision and add

boxescollected +=1; 

To know which box collided, we need to add tag to differentiate our boxes. Lets add tags "catch" and "box" and assign to our boxes.

Select box and in the inspector under tag, click add tags. In the tags, click + sign  and add "catch" in tag 0. click + again and add "box" in tag 1.

Select our box again and set tag to "box". Select catch and set tag to "catch". 

Save project. 

Select "catch up" in the heirachy and drag C# script from script folder and drop in the inspector panel.

 Save project

Next: Complete our C# code 


No comments:

Post a Comment