0
\$\begingroup\$

I'm trying to make a button to make a gameobject rotate and stay rotating in its own axis (Y) but I cannot make it work...

As far as I know it's very simple:

  1. Create an empty gameobject (or whatever you want)
  2. Make a script and attach it to the gameobject
  3. Create public methods
  4. Link the gameobject with the script attached to the button onClick event
  5. Click the button and test the script

My problem is that I don't know how I'm wrong here are the scripts of my project

This first script is my attempt using keys, and it works like charm

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurntableRotation : MonoBehaviour 
{
    public GameObject turntable;
    public float turnSpeed;
    public bool canRotate = false;

    void Start () 
    {
    }

    void Update () 
    {
        StartTurntableRotation();

        StopTurntableRotation();
    }

    public void StartTurntableRotation()
    {
        if (Input.GetKey(KeyCode.I))
            {
                canRotate = true;
            }

            if (canRotate)
            {
                turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
            }
    }

    public void StopTurntableRotation()
    {
        if (Input.GetKey(KeyCode.P))
        {
            canRotate = false;
        }

        if (!canRotate)
        {
            turntable.transform.Rotate(0,0,0);
        }
    }
} 

This second script is my work in progress

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurntableUIBtns : MonoBehaviour 
{    
    public GameObject turntable;
    public float turnSpeed;

        //This is my public method used by the button
    public void StartTurntableBtn()
    {

                //This is my attempt to write the code for the object to rotate
        turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
    }
} 

As far as my knowledge goes, it is supposed to work, but I have to click every time to rotate my object, my goal is to click the button and make the object rotate and stay rotating

\$\endgroup\$
2
\$\begingroup\$
bool canRotate = false;
void Update()
{
    if(canRotate)
        turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
}
//Your button Method
public void StartRotation()
{
    canRotate = !canRotate;
}
\$\endgroup\$
0
\$\begingroup\$

That’s because you need to use the Rotate function in Update, just like you do in your first script. You can simply use a bool again.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.