Search Unity

How to play a audio clip at the point where a raycast hits

Discussion in 'Scripting' started by noahmosel73, Jun 16, 2018.

  1. noahmosel73

    noahmosel73

    Joined:
    Jun 16, 2018
    Posts:
    2
    Here is my code so far

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class ShootingScript : MonoBehaviour {
    4.  
    5.     public float damage = 10f;
    6.     public float range = 100f;
    7.     public float Force = 30f;
    8.     public float FireRate = 10f;
    9.  
    10.     public Camera fpsCam;
    11.     public ParticleSystem muzzleflash;
    12.     public GameObject impactEffect;
    13.     public AudioSource shootSFX;
    14.     public AudioSource impactSFX;
    15.  
    16.     private float nextTimeToFire = 0f;
    17.  
    18.     private void Update()
    19.     {
    20.         if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
    21.         {
    22.             nextTimeToFire = Time.time + 1f / FireRate;
    23.             Shoot();
    24.         }
    25.     }
    26.  
    27.  
    28.     void Shoot ()
    29.     {
    30.         muzzleflash.Play();
    31.         shootSFX.Play();
    32.  
    33.         RaycastHit hit;
    34.         if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
    35.         {
    36.             Debug.Log(hit.transform.name);
    37.  
    38.             TargetScript target = hit.transform.GetComponent<TargetScript>();
    39.             if (target != null)
    40.             {
    41.                 target.TakeDamage(damage);
    42.             }
    43.  
    44.             if (hit.rigidbody != null)
    45.             {
    46.                 hit.rigidbody.AddForce(-hit.normal * Force);
    47.             }
    48.  
    49.             GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
    50.             if (impactGO != null)
    51.             {
    52.                 impactSFX.Play(); //Want to play at the point of impact
    53.                 Destroy(impactGO, 1.5f);
    54.             }
    55.         }
    56.  
    57.     }
    58. }
    59.  
    Destroy(impactGO, 1.5f);
    }
    }

    }
    }
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
  3. noahmosel73

    noahmosel73

    Joined:
    Jun 16, 2018
    Posts:
    2
    I couldn't figure it out using that but for once the unity guide helped and I just got it
     
  4. new2vrdev

    new2vrdev

    Joined:
    Sep 8, 2019
    Posts:
    1
    Any chance you could share? I am also a new dev trying to figure this out and am having trouble.


    Thanks so much!