0
\$\begingroup\$

I'm newbie to Unity and attempting to move a prefab's arm up and down on a button click but having some difficulty.

The arm movement works when called from the Update() method without checking for a button click. Here's a sample of the code:

[SerializeField] Transform rightArm;
int iRotationSpeed = 100;

void Update()
{
    if (Input.GetButtonUp("Button"))  
    {
        // move the arm up
        rightArm.Rotate(Vector3.up * Time.deltaTime * iRotationSpeed, Space.World);   
     
        // now, move the arm back down        
        rightArm.Rotate(Vector3.down * Time.deltaTime * iRotationSpeed, Space.World);
    }
}

Currently using Unity 2021 Personal.

New contributor
wrappingduke is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

What is your question? You didn't state a specific problem in your post. But what I have found, is that in your first script you rotate something by a tiny amount (Time.DeltaTime is a really small number, say 0.01666... for 60 fps, so you would rotate 100 * 0.016 = 1.6°). It's hard to see these little rotations in the editor, but you rotate the arm right back to it's initial position in the same frame (all code in update is executed once per frame)

if (Input.GetButtonUp("Button") 
{
    rightArm.Rotate(Vector3.up * Time.deltaTime * iRotationSpeed, Space.World); //this rotates by 1.6° upwards
    rightArm.Rotate(Vector3.down * Time.deltaTime * iRotationSpeed, Space.World); //this rotates by 1.6° downwards, in the same frame
}

What you probably meant to do is if button pressed move the arm up, else move the arm down

if (Input.GetButton("Button") 
{
    rightArm.Rotate(Vector3.up * Time.deltaTime * iRotationSpeed, Space.World);
}
else
{
    rightArm.Rotate(Vector3.down * Time.deltaTime * iRotationSpeed, Space.World);
}
\$\endgroup\$
3
  • \$\begingroup\$ The question is more that the code does not work when the button is pressed. GetButtonUp("Button") is correct syntax but as it is will not work if Button is not defined \$\endgroup\$
    – Zibelas
    Commented Jul 10 at 9:54
  • \$\begingroup\$ HI, thanks for the response. It's appreciated. May I ask what additional step(s) is needed to define the Button after adding it to a Scene via the Unity Editor? \$\endgroup\$ Commented Jul 10 at 15:29
  • \$\begingroup\$ You can also just use Input.GetKey_(KeyCode.space) to get whether te space key (or any other key if you replace space) is pressed or not. This is much simpler than defining a button in the unity editor. Another simple method is to add debug logs with Debug.Log("Debug message"); \$\endgroup\$
    – CheckerT
    Commented Jul 10 at 19:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .