如何在单个游戏对象上添加多个音频源
本文关键字:添加 音频 对象 单个 游戏 | 更新日期: 2023-09-27 18:14:30
所以我有一个脚本,当我与标记的游戏对象碰撞时计算点数。我想让游戏在我击中不同物体时发出不同的声音。下面是我的脚本:
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!";
}
}
}
那么我如何为拾取对象和Minus300对象设置不同的声音呢?谢谢你!
你可以链接到字段中的音频源,并在Unity编辑器的检查器中设置它们:
public class POINTS1 : MonoBehaviour
{
public AudioSource pickUpAudio;
public AudioSource minus300Audio;
// ... Use pickUpAudio and minus300Audio instead of GetComponent<AudioSource>()
对于更复杂的情况,另一种选择是使用GetComponents<AudioSource>()
获得AudioSource
组件的数组,然后遍历它们以找到正确的组件。这不仅对您当前的情况不太清楚,而且速度也较慢——尽管在某些情况下可能是必要的。