- Home /
Trying to play other objects' sound and animations from Raycast hit
I just have a raycast coming from the camera, which I want to use to trigger a sound, and start animation playback, on multiple other objects. It's pretty much a 'start' button for the whole scene - activated just by looking.
I don't know what the best way is to simply send the 'play' command to other objects, as I have read about performance hits when searching for objects' name every frame.
Here's the example raycast I'm using at the moment.
#pragma strict
function Start () {
}
function Update () {
// Get the ray going through the center of the screen
var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
// Do a raycast
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
print ("I'm looking at " + hit.transform.name);
else
print ("I'm looking at nothing!");
}
Would really appreciate some guidance and example code for this issue, many thanks in advance!
It depends on your design. Do the other objects have AudioSources and Animation components on them? how do you intend to play the animation? is it legacy or mecanim? - I would just do:
if (the ray hit something)
{
var go = hit.collider.gameObject;
var audio = go.GetComponent<AudioSource>();
if (audio) audio.Play();
var anim = go.GetComponent<Animation>();
if (anim) anim.Play();
}
This will change according to your design - like, you could have only one main audio source that you want to play when you hit those objects, etc.
Give us more info and we'll give you more help.
Answer by jjplay175 · Sep 13, 2014 at 07:02 AM
Not 100% sure but I think I have an idea of how you can achieve the play sound, would it be possible to have a private Gameobject Var and set what ever the raycast is looking at as the variable and then have the same script on every object and just play that, I'm not sure how that would go for performance though
I only code in c# so you might have to fix any mistakes
private var Active : Gameobject;
function Update () {
// Get the ray going through the center of the screen
var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
// Do a raycast
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
if (Active == hit)//If object is the target return
{
continue;}//Continue looking for new target
else
{
Active = hit;//Set viewed object as target
var SelSong = Active.Getcomponent<SongScript>();
SelSong.enabled = true;
print ("I'm looking at " + hit.transform.name);
}
else
print ("I'm looking at nothing!");
}
I hope that helps, it might need a few changes but the general idea should work, hope it helps, I'm quite new to this myself ^^
Your answer
Follow this Question
Related Questions
stop triggers from retriggering animation 2 Answers
Raycasting Door Animator 1 Answer
Continuous RayCast on GetButtonDown 0 Answers
C# - Trigger Animation with Raycasting? 1 Answer
Raycast to trigger audio from other script on hit? 2 Answers