I'm currently trying to set up a code in C# that identifies when a certain button is pressed and when it is released
I'm trying to make this certain button scale down when pressed and scale up when released
public class clickshake : MonoBehaviour
{
public GameObject click;
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
transform.localScale += new Vector3(-0.1F, -0.1f, 0);
}
if (Input.GetMouseButtonUp(0))
{
transform.localScale += new Vector3(0.1F, 0.1f, 0);
}
}
}
by making this script exclusive to the button in its On Click command it only grew the button in size and didn't shrink it down
making this script exclusive to the button in its On Click command
that makes little sense. Especially since the Update
method is called all the time every frame. So calling it additionally from the onClick
will call it twice in that frame. Also from Button.onClick
Note that
EventType.MouseDown
andEventType.MouseUp
are called prior toonClick
.
You can eg use the IPointerDownHandler
and IPointerUpHandler
interfaces to implement that
public class clickshake : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
//Detect current clicks on the GameObject (the one with the script attached)
public void OnPointerDown(PointerEventData pointerEventData)
{
transform.localScale -= new Vector3(0.1F, 0.1f, 0);
}
//Detect if clicks are no longer registering
public void OnPointerUp(PointerEventData pointerEventData)
{
transform.localScale += new Vector3(0.1F, 0.1f, 0);
}
}
Note
Ensure an
EventSystem
exists in the Scene to allow click detection. For click detection on non-UI GameObjects, ensure aPhysicsRaycaster
is attached to the Camera.
and non-UI objects ofcourse will also need a Collider
.
Input.GetMouseButtonDown(0)
is triggered when the button is pressed , since you call it when the button is already pressed, it doesn't trigger.
Input.GetMouseButtonDown
Returns true during the frame the user pressed the given mouse button.
https://docs.unity3d.com/ScriptReference/Input.GetMouseButtonDown.html
try tu use Input.GetMouseButton(0)
instead.
Or call it elsewhere than in the OnClick()
.
But be aware that Input.GetMouseButton(0)
if in a loop, will trigger multiple time since its detects when the button is held down.
EDIT By trigger I mean that its returns True
so it triggers your if
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.