- Home /
How to rotate boject using UI button?
I want to make UI button that after clinking on it and hold will rotate object.
I wrote script but it only rotates object everytime button its clicked. Seem like Update function doesnt work after writting ("float a")
public void Update (float a)
{
if(a==1)
transform.Rotate (new Vector3 (0, 10, 0));
}
How to make object rotate whilke UI button being held down?
Answer by Cocobongo · Jan 14, 2015 at 03:49 PM
The Update()
method needs to remain parameterless, or Unity won't call it.
As @Mmmpies said, you could use a boolean variable to toggle between rotating and not rotating states.
So, all in all, something like:
private bool _rotate;
void Update()
{
if(_rotate)
{
transform.Rotate(new Vector3(0, 10, 0));
}
}
public void OnPress()
{
_rotate = true;
}
public void OnRelease()
{
_rotate = false;
}
Attach an Event Trigger to your button and have its OnPointerUp
and OnPointerDown
linked to OnPress()
and OnRelease()
I realize this is mostly rephrasing what @$$anonymous$$mmpies already proposed. Feel free to update your post and I'll delete my answer if this annoys you.
It's fine @cocobongo you spotted the Update issue as well. It's not like I can cash karma points in anywhere.
Ah, thank you guys! I was already so close. I was lacking "private bool a" co all cunctions was crying that "a" doesnt exist in curently context.
Thank both of you :) (sorry i cant upvote you but i dont have enought reputation :C) Thanks again!
Answer by Mmmpies · Jan 14, 2015 at 03:27 PM
I guess you have an OnClick event. If so then change that to onPointerDown event and call a public function in your script to set a bool to true.
Add another event onPointerUp that calls another function to set that bool to false.
Then in Update if MyBool = true rotate.
Sorry for not putting all the code I'm typing on my phone.
Should have said Add Component Event Trigger to access the pointer down and up.
EDIT:
Well @Cocobongo pretty much wrote the entire thing out for you so what's the problem?
-EDITED- This was written before @Cocobongo reply.
You helped alot, thanks.
Answer by unity_wXpbF151lxS5ug · Sep 25, 2018 at 08:00 AM
Dear Cocobongo and Mmmpies,
Your answers have clarified my problem too, thanks. Because I used to have a similiar problem with Zer0Frost had. Your opinions worked like a charm. :) Finding answers even after 3 years is cool.
Thank you.
Your answer
Follow this Question
Related Questions
How can I bind a custom object or variable to an UI button? 2 Answers
UI button does not press if colliding with other UI object 1 Answer
I want to make responsive homescreen. how to make responsive homescreen UI like this example ? 0 Answers
How to display UI elements in front of the gameObject? 1 Answer
Unity UI Button states 1 Answer