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

How to add multiple audio sources on a single game object?

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

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 对象发出不同的声音呢?谢谢!

您可以link到字段中的音频源,并在Unity编辑器的检查器中设置它们:

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

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