Button Get Mouse Button Up

hi, i have a little problem with my code, when i release it goes so fast that we can’t see the button effect i made, i mean we can’t see the button taking his initial size.

any suggestions. here is the code :

function Update ()
{

        var hit : RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
	
	if (Input.GetMouseButtonDown(0))
	{
 		if(hit.collider.name == "Button")
       	{
       		gameObject.Find("Button").transform.localScale = Vector3 (0.9, 0.9, 1);
       	}
	}
	
	if (Input.GetMouseButtonUp(0))
	{
		gameObject.Find("Button").transform.localScale = Vector3 (1, 1, 1);
		gameObject.Find("Main Camera").transform.position.x = -5;
	}
}

I don’t see any problems with the code. The button should shrink when it is clicked and return to original size when the button is released.

Your code is very expensive in terms of performance

  • You perform a raycast every frame
  • You use find to get a GameObject instead of using the reference you already have
  • You resize the button every time the mouse is released. Again using a find and a find

Try out the following code for size. (C#, not checked for errors).

private bool isButtonClicked;
private Transform button;

void Update(){
    if(Input.GetMouseButtonDown(0)){
        RayCastHit2D hit = new Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
        if(hit.collider.name == "Button"){
            button = hit.transform;
            button.localScale = new Vector3 (0.9f,0.9f,0.9f);
            isButtonClicked = true;
        }
    }
    if(isButtonClicked && Input.GetMouseButtonUp(0)){
        button.localScale = Vector3.one;
        isButtonClicked = false;
    }
}