如何为拾音器添加声音?

时间:2016-10-13 09:26:48

标签: c# audio unity3d

好吧,所以我最近进入了Unity,我从学校得到了一份任务,我决定制作一款具有镜子边缘感觉的游戏,但是更加基本的是滚动球。问题是我试图放的拾音器没有发出任何声音。我不知道如何解决它,我已经尝试查找解决方案,但它不会工作。任何人都可以帮助我吗?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Player_Controller : MonoBehaviour
{
    public float speed;
    public Text countText;
    private Rigidbody rb;
    private int count;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText();
    }

    void FixedUpdate()
    {
        float moveHorizonal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizonal, 0.0f, moveVertical);

        rb.AddForce(movement * speed);
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("pickup"))
        {
            AudioSource audio = GetComponent<AudioSource>();            

            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText();           
        }
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
    }
}

2 个答案:

答案 0 :(得分:1)

声音不会播放,因为您甚至在脚本中的任何位置调用播放功能。如果声音附加到同一个GameObject上,Player_Controller脚本附加到,则只需在“开始”功能中执行AudioSource audio = GetComponent<AudioSource>();,然后在audio.Play();函数中执行OnTriggerEnter

public float speed;
public Text countText;
private Rigidbody rb;
private int count;

AudioSource audio;
void Start()
{
    audio = GetComponent<AudioSource>();
    rb = GetComponent<Rigidbody>();
    count = 0;
    SetCountText();
}

void FixedUpdate()
{

    float moveHorizonal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizonal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("pickup"))
    {
        audio.Play(); //Play it

        other.gameObject.SetActive(false);
        count = count + 1;
        SetCountText();
    }

}

void SetCountText()
{
    countText.text = "Count: " + count.ToString();
}

现在,如果声音附加到您选择的每个游戏对象上,您应该使用GetComponent来获取该对撞机上的AudioSource然后播放它。

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("pickup"))
    {
        AudioSource audio = other.GetComponent<AudioSource>(); //Get audio from object
        audio.Play(); //Play it

        other.gameObject.SetActive(false);
        count = count + 1;
        SetCountText();
    }
}

答案 1 :(得分:0)

将另一个设为无效

other.gameObject.SetActive(false);

声音会播放。