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

Botton

Discussion in 'Scripting' started by Arhaela, Jan 10, 2020.

  1. Arhaela

    Arhaela

    Joined:
    Jan 10, 2020
    Posts:
    5
    i was making simple 2d game from tutorial and I thought I would try to make it mobile,
    I need help how to write script for the button; if i click the button it will be read as up key on
    keyboard, or any key on keyboard (1 button per 1 key) i have controls for they keys and i don't want to write everything from beginning (well i cannot write cause i have no idea what i'm doing)
     
    Last edited: Jan 10, 2020
  2. olejuer

    olejuer

    Joined:
    Dec 1, 2014
    Posts:
    210
    You say you have controls for keyboard input already. How does that look?
    If it is somethink like this
    Code (CSharp):
    1. private void Update() {
    2.   if(Input.GetKeyDown(KeyCode.A)) {
    3.     PressA();
    4.   }
    5. }
    6.  
    7. private void PressA() {
    8.   // handle input
    9. }
    then your button could just call
    PressA()
    as well and the A-key and the button would have the same effect. Is this what you want?
     
  3. Arhaela

    Arhaela

    Joined:
    Jan 10, 2020
    Posts:
    5
    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxY) {
    2.             camAnim.SetTrigger("shake");
    3.             Instantiate(moveEffect, transform.position, Quaternion.identity);
    4.             targetPos = new Vector2(transform.position.x, transform.position.y + increment);
    5.         } else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minY) {
    6.             camAnim.SetTrigger("shake");
    7.             Instantiate(moveEffect, transform.position, Quaternion.identity);
    8.             targetPos = new Vector2(transform.position.x, transform.position.y - increment);
     
  4. Arhaela

    Arhaela

    Joined:
    Jan 10, 2020
    Posts:
    5
    i would want something like if i clickbutton on screen it would have same effect as clicking button on keybord
     
  5. olejuer

    olejuer

    Joined:
    Dec 1, 2014
    Posts:
    210
    You have to rewrite this like so:
    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.UpArrow))
    2. {
    3.   PressUp();
    4. }
    5.  
    6. private void PressUp()
    7. {
    8.   if(transform.position.y >= maxY) return;
    9.   camAnim.SetTrigger("shake");
    10.   Instantiate(moveEffect, transform.position, Quaternion.identity);
    11.   targetPos = new Vector2(transform.position.x, transform.position.y + increment);
    12. }
    and then your button can also call the PressUp() function.