C# Game Programming Cookbook for Unity 3D / Программирование игр на Unity 3D C#. Книга готовых решений.: 8.1.1 Разбор скрипта

Оглавление
Английский оригинал Перевод на русский

Сожалеем, но текст оригинала доступен только зарегистрированным пользователям.

using UnityEngine;
using System.Collections;
public class SoundObject
{
public AudioSource source;
public GameObject sourceGO;
public Transform sourceTR;
public AudioClip clip;
public string name;
public SoundObject(AudioClip aClip, string aName, float aVolume)
{ // in this (the constructor) we create a new audio source // and store the details of the sound itself sourceGO= new GameObject("AudioSource_"+aName);
sourceTR= sourceGO.transform;
source= sourceGO.AddComponent<AudioSource>();
source.name= "AudioSource_"+aName;
source.playOnAwake= false;
source.clip= aClip;
source.volume= aVolume;
clip= aClip;
name= aName;
}

ilia1395 25.10.14 в 21:18

0

public void PlaySound(Vector3 atPosition)
{
sourceTR.position= atPosition;
source.PlayOneShot(clip);
}
}

ilia1395 25.10.14 в 21:30

0

public class BaseSoundController : MonoBehavior
{
public static BaseSoundController Instance;
public AudioClip[] GameSounds;
private int totalSounds;
private ArrayList soundObjectList;
private SoundObject tempSoundObj;
public float volume= 1;
public string gamePrefsName= "DefaultGame"; // DO NOT FORGET TO SET
// THIS IN THE EDITOR!!

ilia1395 25.10.14 в 21:30

0

public void Awake()
{
Instance= this;
}
void Start ()
{

ilia1395 25.10.14 в 21:30

0

Mac OS X: ~LibraryPreferencesUnityWebPlayerPrefs
Windows: %APPDATA%\Unity\WebPlayerPrefs

ilia1395 25.10.14 в 21:36

0

// we will grab the volume from PlayerPrefs when this script
// first starts
volume= PlayerPrefs.GetFloat(gamePrefsName+"_SFXVol");

ilia1395 25.10.14 в 21:36

0

soundObjectList=new ArrayList();

ilia1395 25.10.14 в 21:36

0

foreach(AudioClip theSound in GameSounds)
{

ilia1395 25.10.14 в 21:37

0

tempSoundObj= new SoundObject(theSound,
theSound.name, volume);
soundObjectList.Add(tempSoundObj);

ilia1395 25.10.14 в 21:37

0

totalSounds++;
}
}

ilia1395 25.10.14 в 21:37

0

public void PlaySoundByIndex(int anIndexNumber, Vector3 aPosition)
{

ilia1395 25.10.14 в 21:37

0

if(anIndexNumber>soundObjectList.Count)
{
Debug.LogWarning("BaseSoundController>Trying to do
PlaySoundByIndex with invalid index number. Playing
last sound in array, instead.");
anIndexNumber= soundObjectList.Count-1;
}

ilia1395 25.10.14 в 21:38

0

A temporary AudioClip is made to hold the required sound as it is played with
AudioSource.PlaySound():

ilia1395 25.10.14 в 21:38

0

tempSoundObj= (SoundObject)soundObjectList[anIndexNumber];
tempSoundObj.PlaySound(aPosition);
}
}

ilia1395 25.10.14 в 21:38

0
Минутку...