- Home /
 
Change image on keypress
Hello how can i make a script which when i press and hold a key change the sprite of an object and when i leave it changes the spirte back to the original? Thank you.
Answer by UnityCoach · Apr 10, 2017 at 02:03 PM
There are many ways to do it. I would probably use an Animator Controller with states and animation, but as I don't know what you want to do, here's some code to do it. It's not optimised at all though.
 public Sprite spriteA;
 public Sprite spriteB;
 void Update ()
 {
     if (Input.GetKeyDown (Keycode.P)
     {
         GetComponent<SpriteRenderer>().sprite = spriteA;
     }
     if (Input.GetKeyUp (Keycode.P)
     {
         GetComponent<SpriteRenderer>().sprite = spriteB;
     }
 }
 
              Answer by Sergiozed · Apr 10, 2017 at 07:25 PM
Ty for the answer first :) Basically I am making a little piano game with 10 keys and i want that when i press a key on keyboard i play the sound and also i want to make more visible the key being pressed on the piano, so I made a sprite of normal white key and one "pressed" key which is blue but i didn't really understand how the code language works. I mean as you wrote, you have sprite A and sprite B but how can i make the script load the file? Do i need to put the path of the image or the files just needs to be in assets? Oh, and what is function to load and play a sound? Thank you very much! :)
Answer by kchhibber · Apr 10, 2017 at 07:22 PM
You could use the following code: Using UnityEngine.UI; //Include this to work with Unity UI Image elements
 Image myImageComponent; // Image component attached to this gameobject
 
 public Sprite originalSprite;
 public Sprite pressedSprite;
 
 
  void Start() //Lets start by getting a reference to our image component.
  {
  myImageComponent = GetComponent<Image>();
  }
 
 void Update()
 {
 if(Input.GetKey(KeyCode.D))
 {
 myImageComponent.sprite  = pressedSprite;
 }
 else if(Input.GetKeyUp(KeyCode.D))
 {
 myImageComponent.sprite = originalSprite;
 }
 }
 
               Hope this helps!
Your answer
 
             Follow this Question
Related Questions
How do i change a sprite when another gameobject with the same prefab is colliding / is near 1 Answer
Sprite image not changing 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to get pivot of sprite in script 2 Answers