Unity Tutorial – Touch Hold to Grow and Shrink Game Object

In this tutorial we will explore how to work with the Touch Stationary selection inside of Unity Touch Functionality. In this project we have two 3D cubes which will be used to test the touch functionalities where you can touch and hold on the object and it grow to 3 points and when it does it will start to shrink down to 1 point in scale.

Lesson objective –

  1. Create a Touch and Hold app in Unity using C#
  2. Using the Touch Phase Stationary to interact with 3D Cube.
  3. Limit the Growth and Shrink of the 3D Object in Real Time
  4. use the same method on Multiple objects in the same scene

 

Full Video Tutorial on How to Scale Game Objects using Touch and Hold in Unity and C#

 

Full Script for this project –

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HoldAndScaleObjects : MonoBehaviour
{
    Vector3 scaleChange = new Vector3(-0.01f, -0.01f, -0.01f);

    private GameObject selectedObject;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Stationary)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position);

            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.tag == "cube")
                {
                    selectedObject = hit.collider.gameObject;

                    selectedObject.transform.localScale += scaleChange;

                    if (hit.transform.localScale.y < 1f || hit.transform.localScale.y > 3f)
                    {
                        scaleChange = -scaleChange;
                    }

                }
            }
        }
    }
}

 




Comments are closed.