2015-09-25 33 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 –

相關問題