c# - 如何在单个游戏对象上添加多个音频源?

标签 c# audio unity3d scripting

因此,我有一个脚本,当我与带标签的游戏​​对象发生碰撞时会计算分数。我希望游戏在击中不同物体时发出不同的声音。所以这是我的脚本:

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

public class POINTS1 : MonoBehaviour
{

public Text countText;
public Text winText;



private int count;


void Start()
{

    count = 0;
    SetCountText();
    winText.text = "";
    PlayerPrefs.SetInt("score", count);
    PlayerPrefs.Save();
    count = PlayerPrefs.GetInt("score", 0);
}



void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Pickup"))
    {
        other.gameObject.SetActive(false);
        count = count + 100;
        SetCountText();
    }


    else if (other.gameObject.CompareTag("minus300"))
    {
        other.gameObject.SetActive(false);
        count = count - 300;
        SetCountText();
        {
            GetComponent<AudioSource>().Play();
        }
    }

    PlayerPrefs.SetInt("score", count);
    PlayerPrefs.Save();
    count = PlayerPrefs.GetInt("score", 0);
}

void SetCountText()
{
    PlayerPrefs.SetInt("score", count);
    PlayerPrefs.Save();
    count = PlayerPrefs.GetInt("score", 0);
    countText.text = "Score: " + count.ToString();
        if (count >= 5000)
        {
            winText.text = "Good Job!";
        }
    }


}

那么,PickUp对象和Minus300对象如何产生不同的声音?谢谢!

最佳答案

您可以链接到字段中的音频源,并在Unity编辑器的检查器中进行设置:

public class POINTS1 : MonoBehaviour
{
    public AudioSource pickUpAudio;
    public AudioSource minus300Audio;
    // ... Use pickUpAudio and minus300Audio instead of GetComponent<AudioSource>()

对于更复杂的情况,一种替代方法是使用 GetComponents<AudioSource>() 获取AudioSource组件数组,然后遍历它们以找到合适的组件。这不仅对于您当前的情况不太清楚,而且速度较慢-尽管在某些情况下可能有必要。

关于c# - 如何在单个游戏对象上添加多个音频源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32788105/

相关文章:

c# - C#中如何获取与文件扩展名关联的推荐程序

c# - 异步方法中的 Task.Run() 导致线程池饥饿?

c# - 预定义列表容量

android - 将android eclipse库添加到unity3d项目

c# - 如何使 2d Sprite 在按键方向上以平滑的宽弧线移动?

c# - 执行标量 : "Connection not initialized"

java - 奇怪的 Math.sin 行为

java - 如何在单个文件中记录MediaPlayer输出和语音?

audio - 在音频文件集合中查找指定的音频模式

c# - unity 3D中的反转动画