Unity 3D Game Engine – Android – Tap Single – New Object – Instantiate – JS

Instantiate new objects by tapping on Android Devices (Unity JavaScript).

1. Hierarchy create the structure:

– Cube (Game Object)
– Main Camera X=0 Y=0 Z=-10, attach the ‘TapInstantiate.js’

TapInstantiate.js


// Main Camera> Inspector> assign a Gameobject of Prefab
var bullet : Transform;

function Update () {  
    
		// Se c'è un tocco  AND  la fase è il primo contatto del dito con il display
		if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
		// Your 2D vector
		var touchPos = Input.GetTouch(0).position;

		// New 3D vector with the Z co-ordinate
		// As your camera's Z is at -10, setting it to 10 will create it at 0 in the world
		// Change z value to instantiate the object near or far the Camera 
		var createPos = Camera.main.ScreenToWorldPoint(Vector3(touchPos.x, touchPos.y, 10));

		Instantiate(bullet, createPos, Quaternion.identity);
        }
}

2. Hierarchy> Main Camera> Inspector> TapInstantiate.js> DRAG AND DROP Cube over public var bullet