THIS CONTENT DOWNLOAD SHORTLY

Objective

Main objective of this blog post is to give you an idea about Button Click Effect in Unity.

 

 

Step 1 Introduction

You can give click effect to a button through animation or scripting. Here is a way to give click effect via scripting.

  • button
  • button-script

[Button having ButtonClick Script]

As we can see in the above image there are following variables in inspector for ButtonClick script.

From Used to set scale of button at start.
To Used to set scale of button when it’s being clicked.
 

Step 2 Code Sample

ButtonClick Script:

/// <summary>
/// Button Click Effect
/// </summary>
[RequireComponent(typeof(Button))]
public class ButtonClick : MonoBehaviour
{
          public Vector3 from = Vector3.one;
          public Vector3 to = Vector3.one * 0.95f;
 
          void Start()
          {
GetComponent<Button>().onClick.AddListener(() =>
StartCoroutine(Scaling()));
    GetComponent<RectTransform>().localScale = from;
          }
    
          IEnumerator Scaling ()
          {
               GetComponent<RectTransform>().localScale = to;
               yield return new WaitForSeconds(Time.fixedDeltaTime * 3);
               GetComponent<RectTransform>().localScale = from;
          }
}
 

Step 3 Explaination

[RequireComponent(typeof(Button))] For this script ‘Button’component is required.
GetComponent <Button>().onClick.AddListener(() =>StartCoroutine(Scaling())) Here scaling co-routine is added to OnClick Event of Button component. Thus this co-routine works when the button is clicked.
WaitForSeconds(Time.fixedDeltaTime * 3) Time to wait for scaling button to ‘To-scale’ from ‘From-scale’.

I hope you find this blog is very helpful while working with Button click effect in Unity. Let me know in comment if you have any question regarding unity.

Got an Idea of Game Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Game Development Company in India.

I am 3D Game developer with an aspiration of learning new technology and creating a bright future in Information Technology.