Search Unity

can't make my UI buttons move the player

Discussion in 'Scripting' started by brunoenvia, Aug 21, 2019.

  1. brunoenvia

    brunoenvia

    Joined:
    Aug 5, 2019
    Posts:
    94
    i'm trying to make my player move in both directiona i've tried this tutorial
    but it's not working


    this is how it looks like
    upload_2019-8-21_20-44-26.png
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Your Button Script has no OnClick functionality attached. Attach a script to your gameobject you want to move, that contains all the movement functions you want (like MoveRight() and MoveLeft()), then drag your gameobject to where there is "None" in OnClick on your image. Then select the right function for the button, ie MoveLeft() for the left button.

    Edit: The video you posted instead imports some assets and adds a script to the button that handles the movement for him. If you want to do that, use the same asset and closely watch what he does in the video.
     
  3. brunoenvia

    brunoenvia

    Joined:
    Aug 5, 2019
    Posts:
    94
    yes i did that but the player doesn't move continuously when i keep holding the UI button
    how can i make that happen?
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    I dont have a lot of experience with EventTriggers, but i'd assume OnClick is only called once per, well, click.
    There may or may not be an EventTrigger that continuously sends signals while it is active. Maybe someone else can help out here. You could add an EventTrigger component to your buttons and experiment with that, but in case such a trigger does not exist, here is what you could do:

    Implement an integer and when a button gets pressed, set its value to 1 or -1 depending on the direction. When the button gets released, set the value back to 0 (so you need an EventTrigger for pressed and released).
    In the Update() loop of your movement script then simply add your movement, multiplied with the integer, to your position each frame. This makes you move left, right, or not at all based on the button interaction. So you'd end up with something like this:
    Code (CSharp):
    1. int moveDirection = 0; // make your button clicks set this 1 for right, -1 for left, 0 for standing still
    2. int movementSpeec = 5; // how fast you want to go
    3.  
    4. void Update(){
    5.     transform.position += transform.right * moveDirection * movementSpeed * Time.deltaTime;
    6. }