- Home /
Clicking Game Object Scrpit
I'm trying to create a script where if I click on a certain game object, it plays an audio source. So far I got it to play the audio source whenever I click the mouse button but I only want it to play if I click a certain game object.
Answer by AntiLunchBox · Jun 20, 2013 at 05:33 PM
Depends what platform you are planning to use. In both situations you have to throw a collider on the GameObject.
If you aren't building to mobile, only platforms that use mouse clicks -- you could just throw a script that has an OnMouseDown function on it that calls audio.Play();
For a more general approach, you want to use Raycasting. Here is an example:
if ( Input.GetMouseButtonDown(0)){
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 100.0))
if(hit.collider.transform == target)
target.audio.Play();
}
$$anonymous$$eep in $$anonymous$$d that for different platforms, the input is different. like Input.touches
It doesn't seem to be working for me. What variables do I need? And would I replace target with the Game Object?
yes you would replace target with the gameobject that has the audiosource on it that you want to play
also, you can just do Physics.Raycast(ray,hit)
If you look at the raycasting link i sent you, it says what the variables mean. the 100 gives it a maximum distance of 100. If the object is 100 away from the camera, it won't trigger.
Answer by juliancruz · Jun 20, 2013 at 08:38 PM
Add collider component to object and reference the audio.
void OnMouseDown() { sound.Play(); }
Your answer
Follow this Question
Related Questions
How to play an audio one shot clip on a collision 1 Answer
Click to destroy object 2 Answers
Audio Help! 1 Answer
help sound on collision when key down 2 Answers