1、加载本地资源:
using UnityEngine;
using System.Collections;
public class LoadResources : MonoBehaviour {
private AudioSource _Audio;
IEnumerator Start(){
_Audio=this.gameObject.AddComponent<AudioSource>();
WWW www=new WWW(string.Format("file://{0}/music.unity3d",Application.dataPath));
yield return www;
if(www.error==null){
_Audio.clip=www.assetBundle.mainAsset as AudioClip;
}
else Debug.LogError(www.error);
}
void Update(){
if(!_Audio.isPlaying)_Audio.Play();
}
}
2、加载远程资源:
using UnityEngine;
using System.Collections;
public class LoadResources : MonoBehaviour {
private AudioSource _Audio;
IEnumerator Start(){
_Audio=this.gameObject.AddComponent<AudioSource>();
WWW www=new WWW("http://127.0.0.1/music.unity3d");
yield return www;
if(www.error==null){
_Audio.clip=www.assetBundle.mainAsset as AudioClip;
}
else Debug.LogError(www.error);
}
void Update(){
if(!_Audio.isPlaying)_Audio.Play();
}
}
也可以这样写:
using UnityEngine;
using System.Collections;
public class LoadResources : MonoBehaviour {
private AudioSource _Audio;
void Start(){
_Audio=this.gameObject.AddComponent<AudioSource>();
StartCoroutine(Load());
}
private IEnumerator Load(){
WWW www=new WWW(string.Format("file://{0}/music.unity3d",Application.dataPath));
yield return www;
if(www.error==null){
_Audio.clip=www.assetBundle.mainAsset as AudioClip;
}
else Debug.LogError(www.error);
}
void Update(){
if(!_Audio.isPlaying)_Audio.Play();
}
}
或者这样写:
using UnityEngine;
using System.Collections;
public class LoadResources : MonoBehaviour {
private AudioSource _Audio;
IEnumerator Start(){
_Audio=this.gameObject.AddComponent<AudioSource>();
return Load();
}
private IEnumerator Load(){
WWW www=new WWW(string.Format("file://{0}/music.unity3d",Application.dataPath));
yield return www;
if(www.error==null){
_Audio.clip=www.assetBundle.mainAsset as AudioClip;
}
else Debug.LogError(www.error);
}
void Update(){
if(!_Audio.isPlaying)_Audio.Play();
}
}
如果发布成WebGame,则需要在网站中添加跨域访问策略文件crossdomain.xml。
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*" header="*" />
</cross-domain-policy>