2015-09-25 28 views
1

所以我有一个脚本,当我与标记的游戏对象发生碰撞时可以计算点数。当我击中不同的物体时,我想让游戏发出不同的声音。所以这是我的脚本:如何在单个游戏对象上添加多个音频源?

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对象的声音?谢谢!

+0

如果你在这里没有得到答案,你可能还想尝试http://gamedev.stackexchange.com/ – tarun713

回答

2

您可以链接到音频源的领域,使他们在检查中统一编辑:

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

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

+0

绝对美妙的答案,完美工作!感谢:D –

相关问题