- Home /
Raycast to trigger audio from other script on hit?
Hello,
I am having difficulty in understanding how to implement a raycast on one game object, on hit, to trigger audio on another gameobject from another script
This is my raycast script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test01 : MonoBehaviour {
public LayerMask mask;
AudioSource audio;
void Start()
{
// need to access script attached thot his cube // this could be used for all cubes in the 1000
audio = GameObject.FindGameObjectWithTag("Cube1").GetComponent<AudioSource>();
//audio = Cube1.GetComponent<audio>();
}
void Update () {
Ray ray = new Ray (transform.position, transform.forward);
RaycastHit hitInfo;
if (Physics.Raycast (ray, out hitInfo, 100, mask, QueryTriggerInteraction.Collide)) {
print (hitInfo.collider.gameObject.name);
//Destroy (hitInfo.transform.gameObject);
if (hitInfo.collider.isTrigger)
{
Debug.DrawLine (ray.origin, hitInfo.point, Color.red);
//GetComponent<AudioSource>().PlayOneShot ( mySound);
audio.PlayOneShot(mySound);
}
} else {
Debug.DrawLine (ray.origin, ray.origin + ray.direction * 100, Color.green);
}
}
}
This the audio script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class audio : MonoBehaviour
{
public AudioSource myAudioSource; // a private reference to an AudioSource variable
public AudioClip mySound; // a public reference to an AudioClip (sound)
// Start is called before the first frame update
void Start()
{
myAudioSource = GetComponent<AudioSource>(); // finds the AudioSource component within the GameObject
}
// OnTriggerEnter is called when an actor enters the collider
void OnTriggerEnter(Collider other)
{
myAudioSource.clip = mySound;
myAudioSource.Play();
}
}
I feel I am using the wrong trigger maybe? also dont know how to call/reference properly from another script when, i thought calling through getcomponent would do this
I am getting errors saying context? " Assets/Scripts/Test01.cs(33,22): error CS0103: The name 'mySound' does not exist in the current context"
Apologies I am quite new to c#. The desired behaviour is for the raycast to just trigger every time it hits one of this gameobject
Thanks in advance
Answer by dylanfries · Nov 14, 2020 at 08:16 PM
Hi,
You might want to post more info about the error, its not clear what the problem is. I would also be careful destroying the hit object before you are done with it, perhaps it is affecting hitInfo (which references it).
Also, quick trick, you might want to look into Debug.DrawRay as well as it lets you pass the ray itself directly in to draw and can be useful for debugging what is actually being cast when you raycast.
Answer by Rich_XR · Nov 15, 2020 at 10:29 AM
I have edited the question and included the errors as requested.