所以我有一个脚本,当我与标记的游戏对象发生碰撞时会计算点数。当我击中不同的物体时,我希望游戏发出不同的声音。所以这是我的剧本:
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对象提供不同的声音?谢谢!
答案 0 :(得分:2)
您可以链接到字段中的音频源,并在Unity编辑器的检查器中设置它们:
public class POINTS1 : MonoBehaviour
{
public AudioSource pickUpAudio;
public AudioSource minus300Audio;
// ... Use pickUpAudio and minus300Audio instead of GetComponent<AudioSource>()
更复杂情况的另一种选择是使用GetComponents<AudioSource>()
来获取AudioSource
组件的数组,然后遍历它们以找到正确的组件。这不仅对你目前的情况不太清楚,而且速度也慢 - 虽然在某些情况下可能是必要的。