- Home /
gameObject to play sound on deletion, won't work...
I'm trying to "collect" an object, since I no longer need it in the world I delete it with "Delete(gameObject);" and it works perfect. Now I want to play a sound as well, so I have and it works but once the object is deleted the rest of the collectables can't find the audioSource, even if I attach it to them... I've tried attaching the audio to an inanimate object like a Shovel that's part of the scenery but it wont work. Can someone help me to properly attach audio and link it from another object?
I think my problem is that the script I am using is deleting the gameObject and anything it's linked to/with.
var PageCount : GUIText;
var Count : int;
var Pickup : AudioSource;
function Touched(hit:RaycastHit)
{
Destroy(gameObject);
}
function Update () {
if ( Input.GetMouseButtonDown(0)){
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 0.8))
{
hit.transform.SendMessage("Touched", hit, SendMessageOptions.DontRequireReceiver);
Count ++;
PageCount.guiText.text = Count.ToString();
audio.Play();
audio.loop = false;
}
}
}
You're going to have to specify what code is actually part of this script. Bunching everything into one code block without describing stuff isn't going to give us any insight on how to help you solve your problem.
I'm not entirely sure what you mean? I always keep my scripts small so that I don't mix bits up. This is the script for collecting the pages, it's pretty self explanatory since it's a basic raycast/delete script.
So, from my perspective trying to look at your code, the RayCast is being tracked by the same script that it's Send$$anonymous$$essaging to Destroy. So, take for example if you had this script on a cube in an empty scene, you click on it and the Send$$anonymous$$essage is sent to execute Touched, you're going to immediately Destroy() the object.
That in essence means any code that comes after the Send$$anonymous$$essage is probably not going to execute since the GameObject is being destroyed.
That's where my confusion is co$$anonymous$$g from.
Answer by T27M · Oct 14, 2012 at 11:25 PM
Change the type of Pickup to AudioClip assign the clip your trying to play in the inspector and use the audio.PlayOneShot().
var Pickup : AudioClip;
if (Physics.Raycast (ray, hit, 0.8))
{
hit.transform.SendMessage("Touched", hit, SendMessageOptions.DontRequireReceiver);
Count ++;
PageCount.guiText.text = Count.ToString();
audio.PlayOneShot(Pickup);
}
You need to make sure the object that is playing the sound also has a AudioSource component attached to it.
Your answer
Follow this Question
Related Questions
Audio sound on gameObject delete? 1 Answer
Background Music 2 Answers
Audio wont play when conditions are met 1 Answer
Play An Audio Clip When An Instantiated Object Collides 1 Answer