如何在拾音器中添加声音?

本文关键字:添加 声音 拾音器 | 更新日期: 2023-09-27 18:13:03

我最近接触了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();
    }
}

如何在拾音器中添加声音?

声音不会播放,因为你是不是甚至在脚本的任何地方调用播放函数。如果声音被附加到与Player_Controller脚本所附加的相同的GameObject上,你只需要在Start函数中执行AudioSource audio = GetComponent<AudioSource>();,然后在OnTriggerEnter函数中执行audio.Play();

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();
}

现在,如果声音附加到你拾取的每个GameObject上,你应该使用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();
    }
}

设置另一个为非活动

other.gameObject.SetActive(false);