The code only works in Update(), what is the reason?

Hi, can anyone help me with my question? I want to rotate the cube when the Left button is clicked. I have used On Click() function and attached RotateLeft() to it. That function only shows “Called” and does not do anything with the cube, it remains the same, but in the case when I write the code in Update it rotates the cube, what is the problem?
7444226--912665--upload_2021-8-24_14-5-6.png

Presumably OnClick only runs once for 1 frame (the frame you clicked).

So presumably it does work, it just only rotates very very little for 1 frame.

1 Like

at least onclick only happens once per click, update runs every frame.

also *Time.time should be usually *Time.deltaTime

if you want to rotate when mouse button is down, can use this inside update loop:

or if you want to rotate only when selected target object is clicked and mouse button is held down,
i’d use raycast to get target object, then rotate that transform in Update loop

1 Like

My program is for Android and I want the cube to rotate only once. What can I do?

Assuming you want it to rotate smoothly (animate), the general logic could be, have the button set a bool to true (cubeShouldRotate = true;)

And then in update, inside a if (cubeShouldRotate) { } you rotate the cube until it reaches the rotation you want, at which point you set the bool to false.

I did it as you mentioned, but for one time it works very little and i can’t see the difference. Here is the code:
7444547--912752--upload_2021-8-24_16-12-38.png

I think I now the reason why it does not work, but I don’t know the solution. When the On Click() function works the ShouldRotateLeft becomes true only inside function, but when I check the value of ShouldRotateLeft() inside Update is always shows false.

It’s because you immediately set ShouldRotateLeft back to false at the end of Update. Hence, the object rotates for one frame, then stops.

This is effectively doing the exact same thing as your original code.