c# - 玩家拿起物体时触发声音

标签 c# audio unity3d triggers

我在触发声音时遇到麻烦。下面的脚本被附加到带有AudioSource组件和声音剪辑的硬币预制对象上。一切正常,但没有声音。我究竟做错了什么?

using UnityEngine;
using System.Collections;

public class CoinPickup : MonoBehaviour {

    void OnTriggerEnter(Collider other)  // other is a reference to the other trigger collider we have touched
    {
        if (other.gameObject.CompareTag ("Player"))
        {
            gameObject.SetActive (false);
            Debug.Log ("Sound should trigger here.");

            coinSound = gameObject.GetComponent<AudioSource>();
            coinSound.Play();
        }
    }
}

最佳答案

可能不是您想要的东西,但是我通常会实例化这样的声音:(目前我无法访问Unity,因此无法使用)

using UnityEngine;
using System.Collections;

public class CoinPickup : MonoBehaviour 
{
    public AudioSource coinSound; //set in inspector    

    void OnTriggerEnter(Collider other)  // other is a reference to the other trigger collider we have touched
    {
        if (other.gameObject.tag == "Player") //or you could do other.gameObject.name == "Player"
        {
            coinSound.Play(); //play the coin sound
            Destroy(gameobject); // destroy our coin, it has been picked up!
        }
    }
}

我不确定,但是我认为您不能在停用的gameObject上播放声音。

当玩家与硬币接触时,这种方式应该会发出声音,这时它将播放您的声音,然后硬币将自行销毁。

希望这可以帮助 :)

关于c# - 玩家拿起物体时触发声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699861/

相关文章:

c# - 轻量级 C# 持久键值存储?

c# - 文件仅在第一个条件下写入

c# - 并行运行时 IronPDF 死锁

Android解码并保存从 Intent 返回的音频流

android - Android Studio添加声音错误

python - 如何使用winsound同时播放多个声音?

git - 在版本控制中忽略文件夹元文件

c# - 如何使用 C# 在 Windows 上读取连接的 iOS 设备的 UDID?

c# - 将 python 服务器请求转换为统一

c# - 如何在 Unity 2018+ 中获取设备的 IP 地址?