Search Unity

Help with script

Discussion in 'Scripting' started by unity_roBi7Quu7Nk6mA, Nov 15, 2019.

  1. unity_roBi7Quu7Nk6mA

    unity_roBi7Quu7Nk6mA

    Joined:
    Mar 19, 2018
    Posts:
    5
    Hi i'm new to unity and I am making a 3D mobile game but I am having trouble changing my player movement script. I just need to change the Input.GetKey("d") to a UI button instead. thank you so much for your help.
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class PlayerMovement : MonoBehaviour
    5. {
    6.  
    7.     public Rigidbody rb;
    8.  
    9.     public float forwardForce = 2000f;
    10.     public float sidewaysForce = 500f;
    11.  
    12.  
    13.     void FixedUpdate()
    14.     {
    15.         // Add a forward force
    16.         rb.AddForce(0, 0, forwardForce * Time.deltaTime);
    17.  
    18.         if ( Input.GetKey("d") )
    19.         {
    20.             rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    21.         }
    22.         if (Input.GetKey("a"))
    23.         {
    24.             rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    25.         }
    26.  
    27.         if (rb.position.y < -1f)
    28.         {
    29.             FindObjectOfType<GameManager>().EndGame();
    30.         }
    31.     }
    32. }
     
    Last edited: Nov 15, 2019
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    What kind of button do you need to change it to? If a mouse button, you'd use Input.GetMouseButton instead of Input.GetKey. If a UI button, you'll need to learn more about the Unity UI than I can explain in a few sentences, but I'll put a link below to the manual section and you can find tutorials in the Learn section and on YouTube. If another kind of button, you'll have to be specific.

    https://docs.unity3d.com/ScriptReference/Input.GetMouseButton.html
    https://docs.unity3d.com/Manual/UISystem.html
    https://docs.unity3d.com/Manual/UIInteractionComponents.html

    edit: sorry, I missed the "mobile game" part. It is probably the UI button that you're looking for. You create a canvas, a few other steps, then create a button (generally all in the editor). In your script you create a method you want to call when the button is pressed. In the editor you then add the new method to the button's OnClick event. So when the button is pressed that method gets called.
     
  3. unity_roBi7Quu7Nk6mA

    unity_roBi7Quu7Nk6mA

    Joined:
    Mar 19, 2018
    Posts:
    5
    I have already made the UI buttons. What exactly do I type to get the onclick event?
     
  4. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,304