简体   繁体   中英

How to play audio in Unity (Click Event Trigger Cardboard SDK)?

I'm using the Cardboard sdk and have configured Gaze Input Module in Event System. Have also added a collider to my object.

I want to look at the object and play audio when I pull the trigger on my Cardboard HMD. However, it's currently not playing.

Can you advise if the problem is with my code:

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class Kim : MonoBehaviour {

    public GameObject kkhair;
    public AudioSource audio;

    void Start() {
        audio = GetComponent<AudioSource>();
    }

    public void speakKim() {
        audio.Play();
    }
}

This audio does 'play on wake' when that setting is enabled. So I know the file is ok. Just can't make it work for trigger only.

You need to attach an "Event Trigger" component to your GameObject. Select your GameObject in the Hierarchy, click "Add Component", search for "Event Trigger"

Create a new event type of "Pointer Click" Drag in your Kim script, and choose the method speakKim

Your game object should look something like this: 在此处输入图片说明

You must also have an EventSystem in your Hierarchy. If you don't, add one by going to "Create > UI > Event System"

If you have the Cardboard SDK, you should also have the Demo Scene made by Google. There you click a cube that teleports, using the Gaze Input Module. You can use the same mechanism to trigger your audio. The Cube gameObject in that scene has an Event Trigger component that handles the click (and highlighting) for you, and calls a method on another component of the gameObject (in this example the TeleportRandomly() function of the Teleport script attached to the Cube).

在此处输入图片说明

In your case, you could change the Pointer Click event handling to speakKim on your script, to make start the audio playing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM