Search Unity

Question FPS Audio Problem

Discussion in 'Audio & Video' started by abatisara98, Jul 8, 2020.

  1. abatisara98

    abatisara98

    Joined:
    Jul 25, 2019
    Posts:
    8
    Hi everyone,
    I'm having some trouble with my first person character. I would like to add the footstep sound when the player moves, but I don't know how to connect the public void Sound with the movement.
    My Player doesn't have a rigidbody, but just a character controller.
    Here's my script

    Code (CSharp):
    1. public class Player : MonoBehaviour
    2. {
    3.     public CharacterController controller;
    4.     public float speed;
    5.     public float gravity;
    6.     public float jumpHeight;
    7.  
    8.     public Transform groundCheck;
    9.     public float groundDistance;
    10.     public LayerMask groundMask;
    11.     Vector3 velocity;
    12.     bool isGrounded;
    13.  
    14.     public AudioSource Footstep;
    15.     public AudioClip[] FootstepSound;
    16.     void Update()
    17.     {
    18.         isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
    19.         if (isGrounded && velocity.y < 0)
    20.         {
    21.             velocity.y = -2f;
    22.          
    23.         }
    24.         velocity.y += gravity * Time.deltaTime;
    25.         float x = Input.GetAxis("Horizontal");
    26.         float z = Input.GetAxis("Vertical");
    27.         Vector3 move = transform.right * x + transform.forward * z;
    28.      
    29.         controller.Move(move * speed * Time.deltaTime);
    30.         //jump
    31.         if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
    32.         {
    33.             velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    34.         }
    35.         controller.Move(velocity * Time.deltaTime);
    36.         //run
    37.         if (Input.GetKeyDown(KeyCode.LeftShift))
    38.         {
    39.             speed = speed * 2;
    40.      
    41.         }
    42.         else if (Input.GetKeyUp(KeyCode.LeftShift))
    43.         {
    44.             speed = speed / 2;
    45.         }
    46.      
    47.     }
    48.     public void Sound()
    49.     {
    50.         int random = UnityEngine.Random.Range(0, FootstepSound.Length);
    51.         Footstep.PlayOneShot(FootstepSound[random]);
    52.     }
    53. }
    Thanks in advance!