Question by
noahmosel73 · Jun 16, 2018 at 01:07 AM ·
raycastaudioscripting beginner
How to play audio at a point of impact of a raycast
This is my code so far
using UnityEngine;
public class ShootingScript : MonoBehaviour {
public float damage = 10f;
public float range = 100f;
public float Force = 30f;
public float FireRate = 10f;
public Camera fpsCam;
public ParticleSystem muzzleflash;
public GameObject impactEffect;
public AudioSource shootSFX;
public AudioSource impactSFX;
private float nextTimeToFire = 0f;
private void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / FireRate;
Shoot();
}
}
void Shoot ()
{
muzzleflash.Play();
shootSFX.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
TargetScript target = hit.transform.GetComponent<TargetScript>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * Force);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
if (impactGO != null)
{
impactSFX.Play(); //Want to play at the point of impact
Destroy(impactGO, 1.5f);
}
}
}
}
Comment
Answer by aardappel156 · Jun 18, 2018 at 05:21 PM
What I usually do is I do this
public AudioSource pewsound;
if (target != null)
{
target.TakeDamage(damage);
sound.play();
}
And you want to drag the audio in the scene and add the audio source in the inspector on whatever the script is attached too
also, don't forget to turn off "play on awake" in de audio source inspector panel. Hope this help