Unity 3D Tutorial – Add and Remove 2D Game Objects Using Touch Controls
- Subject: Unity 3D Tutorial
- Learning Time: 1 hour
In this tutorial we will explore how to add and remove 2d Sprite images using Touch Controls in Unity 3D using C# Programming. This is going to be the first 2D project we do in the Mobile Development series so its exciting to see how this one will work out. We have got 6 different images to add to this project and as we are dynamically adding sprites to the scene we will also randomize the items in the sprite images and it will choose one out of the six images to apply to the sprite at a time.
Lesson objectives –
- Create a project in unity that spawns and destroys game object on touch
- Work with a 2D Game Template in Unity
- Using custom function to determine the touch position and spawn game objects on empty space
- IF the touch happens on a game object destroy it from the game
- Using Mobile 2D touch controls
- Using Unity Remote with a Android Device
- Using 2D sprites and Lists to spawn random objects to the scene.
Full Video Tutorial On how to add and remove 2D objects in unity using C# programming
Download images for the 2d touch control project here
Add and Remove Items Script
This script will be attached to the Camera in the scene.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AddAndRemoveItems : MonoBehaviour { public List<Sprite> objectList = new List<Sprite>(); public GameObject fruit; // Start is called before the first frame update void Start() { Debug.Log(objectList.Count); } // Update is called once per frame void Update() { if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position); RaycastHit hit; Debug.DrawRay(ray.origin, ray.direction * 100, Color.yellow, 100f); if (Physics.Raycast(ray, out hit)) { if (hit.transform.tag == "fruit") { GameObject temp = hit.transform.gameObject; Destroy(temp); } } else { Touch myTouch = Input.GetTouch(0); MakeFruit(myTouch); } } } private void MakeFruit(Touch TouchPos) { Vector3 objPos = Camera.main.ScreenToWorldPoint(TouchPos.position); objPos.z = 1; fruit.GetComponent<SpriteRenderer>().sprite = objectList[Random.Range(0, objectList.Count)]; Instantiate(fruit, objPos, Quaternion.identity); } }