Unity 3D Game Engine – Android – Tap Single – Specific Object (Tagged) – Counter Increase
Simple JavaScript for Android.
Single Tap a specific object to increase a counter.
Inside Hierarchy create the structure:
– Sphere (Gameobject) -> Inspector> Assign Tag ‘Button1’
– Cube (Gameobject)
– GUI Text (Gameobject)
– Main Camera, attach the script ‘TapControl.js’
TapControl.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)) { // se collidi con un oggetto con tag Button1 if (hit.collider.tag == "Button1"){ // 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> TapControl.js> DRAG AND DROP ‘GUI Text’ (Gameobject) over var scoreText