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