Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Object flip on keypress

Discussion in 'Scripting' started by rudigreig, Feb 20, 2020.

  1. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    I want to make an object go to a certain rotation on a key press, but with the script I currently have it keeps repeating that function. Is there a way to make it stay in one rotation on a key press?
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SpriteFlipper : MonoBehaviour
    6. {
    7.  
    8.  
    9.     private void Update()
    10.     {
    11.  
    12.         if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    13.         {
    14.             transform.Rotate(0, 0, 90);
    15.         }
    16.         if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    17.         {
    18.             transform.Rotate(0,180,90);
    19.         }
    20.     }
    21. }
    22.  
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Input.GeyKey() runs every frame. Try Input.GetKeyDown(), which only runs for one frame after the key is pressed.
     
    Antistone likes this.
  3. rudigreig

    rudigreig

    Joined:
    Dec 11, 2018
    Posts:
    50
    Thank you! It worked!