Unity 3D Game Engine – Android – Tap Single – Counter Increase – JavaScript
This script it is a simple Tap Counter, if you Tap over the objects in the scene counter value will increase.
Inside Hierarchy create the game Objects:
– Sphere (GameObject)
– GUI Text (GameObject)
– Main Camera, attach the ‘TapCounter.js’:
TapCounter.js
#pragma strict // Only ANDROID NOT PC NOT IOS // Attach this script to the Main Camera // Hierarchy DRAG E DROP over var GUI Text in Inspector var scoreText : GUIText; // touch counter, private because the users is not be able to change this value private var score : int; // Ray Cast Setup var speed : float = 4; var hit = new RaycastHit(); function Start () { // The counter initial value is 0 score = 0; scoreText.text = "No Touch:"; } function Update () { // se c'è un tocco Input.touchCount AND la fase del tocco è quella iniziale TouchPhase.Began if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { // traccia i raggi dalla Camera dal punto del tocco var ray = Camera.main.ScreenPointToRay (Input.GetTouch(0).position); // se raycast colpisce l'oggetto if (Physics.Raycast (ray, hit)) { // fai partire la funzione che incrementa il contatore UpdateScore (); } } } function UpdateScore () { // score var increment of +1 score += 1; // scoreText in assigned inside Inspector on GUI Text // change .text property and write it on the display scoreText.text = "Touched: " + score; }
Hierarchy> Main Camera> Inspector> TapCounter.js DRAG AND DROP ‘GUI Text’ (GameObject) over var scoreText