Skip to content

Instantly share code, notes, and snippets.

@smallrice45
Created April 22, 2016 13:15
Show Gist options
  • Save smallrice45/dd505b634721c1f68b72d2865a8a7e1b to your computer and use it in GitHub Desktop.
Save smallrice45/dd505b634721c1f68b72d2865a8a7e1b to your computer and use it in GitHub Desktop.
AssetBundle練習測試
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
public class AssetbundlesMenuItems
{
const string kSimulateAssetBundlesMenu = "AssetBundles/Simulate AssetBundles";
[MenuItem(kSimulateAssetBundlesMenu)]
public static void ToggleSimulateAssetBundle ()
{
AssetBundleManager.SimulateAssetBundleInEditor = !AssetBundleManager.SimulateAssetBundleInEditor;
}
[MenuItem(kSimulateAssetBundlesMenu, true)]
public static bool ToggleSimulateAssetBundleValidate ()
{
Menu.SetChecked(kSimulateAssetBundlesMenu, AssetBundleManager.SimulateAssetBundleInEditor);
return true;
}
[MenuItem ("AssetBundles/Build AssetBundles")]
static public void BuildAssetBundles ()
{
BuildScript.BuildAssetBundles();
}
[MenuItem ("AssetBundles/Build Player")]
static void BuildPlayer ()
{
BuildScript.BuildPlayer();
}
[MenuItem("AssetBundles/Set Asset Bundle From File Name",false, 0)]
static void SetAssetBundlesFromFileNames()
{
if (Selection.assetGUIDs.Length > 0) {
foreach (Object asset in Selection.objects) {
string path = AssetDatabase.GetAssetPath (asset);
string fixPath = "";
string fixAssetName = asset.name;
fixAssetName = fixAssetName.Replace( "Texture", "Mat");
// SpiltString form Path
List<string> pathArray = GameFun.SpiltString(ref path, "/").ToList();
for(int i = 0; i < pathArray.Count-1 ; i++){
// Ignore Assets Folder
if (pathArray[i]=="Asset" || pathArray[i]=="Assets"){
pathArray[i] = "";
}else{
// Fix Folder Path Name
if (pathArray[i]=="Texture"){
pathArray[i] = "Materials";
}
pathArray[i] = pathArray[i] + "/";
}
fixPath += pathArray[i];
}
AssetImporter assetImporter = AssetImporter.GetAtPath (path);
assetImporter.assetBundleName = fixPath+fixAssetName;
Debug.Log (Selection.assetGUIDs.Length + " Asset Bundles Assigned");
}
} else {
Debug.Log ("No Assets Selected");
}
}
}
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class BaseLoader : MonoBehaviour {
const string kAssetBundlesPath = "/AssetBundles/";
// Use this for initialization.
IEnumerator Start ()
{
yield return StartCoroutine(Initialize() );
}
// Initialize the downloading url and AssetBundleManifest object.
protected IEnumerator Initialize()
{
// Don't destroy the game object as we base on it to run the loading script.
DontDestroyOnLoad(gameObject);
#if UNITY_EDITOR
Debug.Log ("We are " + (AssetBundleManager.SimulateAssetBundleInEditor ? "in Editor simulation mode" : "in normal mode") );
#endif
string platformFolderForAssetBundles =
#if UNITY_EDITOR
GetPlatformFolderForAssetBundles(EditorUserBuildSettings.activeBuildTarget);
#else
GetPlatformFolderForAssetBundles(Application.platform);
#endif
// Set base downloading url.
string relativePath = GetRelativePath();
AssetBundleManager.BaseDownloadingURL = relativePath + kAssetBundlesPath + platformFolderForAssetBundles + "/";
// Initialize AssetBundleManifest which loads the AssetBundleManifest object.
var request = AssetBundleManager.Initialize(platformFolderForAssetBundles);
if (request != null)
yield return StartCoroutine(request);
}
public string GetRelativePath()
{
if (Application.isEditor)
return "file://" + System.Environment.CurrentDirectory.Replace("\\", "/"); // Use the build output folder directly.
else if (Application.isWebPlayer)
return System.IO.Path.GetDirectoryName(Application.absoluteURL).Replace("\\", "/")+ "/StreamingAssets";
else if (Application.isMobilePlatform || Application.isConsolePlatform)
return Application.streamingAssetsPath;
else // For standalone player.
return "file://" + Application.streamingAssetsPath;
}
#if UNITY_EDITOR
public static string GetPlatformFolderForAssetBundles(BuildTarget target)
{
switch(target)
{
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.WebPlayer:
return "WebPlayer";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "Windows";
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
case BuildTarget.StandaloneOSXUniversal:
return "OSX";
// Add more build targets for your own.
// If you add more targets, don't forget to add the same platforms to GetPlatformFolderForAssetBundles(RuntimePlatform) function.
default:
return null;
}
}
#endif
static string GetPlatformFolderForAssetBundles(RuntimePlatform platform)
{
switch(platform)
{
case RuntimePlatform.Android:
return "Android";
case RuntimePlatform.IPhonePlayer:
return "iOS";
case RuntimePlatform.WindowsWebPlayer:
case RuntimePlatform.OSXWebPlayer:
return "WebPlayer";
case RuntimePlatform.WindowsPlayer:
return "Windows";
case RuntimePlatform.OSXPlayer:
return "OSX";
// Add more build platform for your own.
// If you add more platforms, don't forget to add the same targets to GetPlatformFolderForAssetBundles(BuildTarget) function.
default:
return null;
}
}
protected IEnumerator Load (string assetBundleName, string assetName)
{
Debug.Log("Start to load " + assetName + " at frame " + Time.frameCount);
// Load asset from assetBundle.
AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetBundleName, assetName, typeof(GameObject) );
if (request == null)
yield break;
yield return StartCoroutine(request);
// Get the asset.
GameObject prefab = request.GetAsset<GameObject> ();
Debug.Log(assetName + (prefab == null ? " isn't" : " is")+ " loaded successfully at frame " + Time.frameCount );
if (prefab != null)
GameObject.Instantiate(prefab);
}
protected IEnumerator LoadGameObject (string assetBundleName, string assetName, System.Action<GameObject> result)
{
Debug.Log("Start to load " + assetName + " at frame " + Time.frameCount);
// Load asset from assetBundle.
AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetBundleName, assetName, typeof(GameObject) );
if (request == null)
yield break;
yield return StartCoroutine(request);
// Get the asset.
GameObject prefab = request.GetAsset<GameObject> ();
Debug.Log(assetName + (prefab == null ? " isn't" : " is")+ " loaded successfully at frame " + Time.frameCount );
if (prefab != null)
result(prefab);
}
protected IEnumerator LoadMaterial (string assetBundleName, string assetName, System.Action<Material> result)
{
Debug.Log("Start to load " + assetName + " at frame " + Time.frameCount);
// Load asset from assetBundle.
AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetBundleName, assetName, typeof(Material) );
if (request == null)
yield break;
yield return StartCoroutine(request);
// Get the asset.
Material prefab = request.GetAsset<Material> ();
Debug.Log(assetName + (prefab == null ? " isn't" : " is")+ " loaded successfully at frame " + Time.frameCount );
if (prefab != null)
result(prefab);
}
protected IEnumerator LoadLevel (string assetBundleName, string levelName, bool isAdditive)
{
Debug.Log("Start to load scene " + levelName + " at frame " + Time.frameCount);
// Load level from assetBundle.
AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(assetBundleName, levelName, isAdditive);
if (request == null)
yield break;
yield return StartCoroutine(request);
// This log will only be output when loading level additively.
Debug.Log("Finish loading scene " + levelName + " at frame " + Time.frameCount);
}
// Update is called once per frame
protected void Update () {
}
}
using UnityEngine;
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class GameFun{
// - 文字分割
public static string[] SpiltString(ref string strText, string strKey){
string[] stringArray = null;
stringArray = strText.Split( new string[] {strKey}, StringSplitOptions.None);
return stringArray;
}
// - 文字擷取
public static string CutStrBeforeKey(ref string strText, string strKey){
string strReturn = "";
int iKeyIdx = strText.IndexOf(strKey);
if (iKeyIdx < 0)
{
// 沒找到關鍵字,則回傳全部
strReturn = strText;
strText = "";
} // end if
else
{
strReturn = strText.Substring(0, iKeyIdx); // 取得"關鍵字"之前的字串
strText = strText.Remove(0, iKeyIdx + strKey.Length); // 刪除包含關鍵字之前的字串
} // end else
return strReturn;
}
// - 文字擷取
public static string CutStrAfterKey(ref string strText, string strKey){
int iKeyIdx = strText.IndexOf(strKey);
if (iKeyIdx < 0){
return "";
}else{
int iKeyLen = strKey.Length;
int iTextLen = strText.Length;
// 取得"關鍵字"之後的字串
string strReturn = strText.Substring( iKeyIdx+iKeyLen
, iTextLen-iKeyIdx-iKeyLen);
// 原字串刪除關鍵字與關鍵字之後的字串
strText = strText.Remove(iKeyIdx, iTextLen-iKeyIdx);
return strReturn;
} // end else
}
// - 氣泡排序法
public static void BubbleSortArray(ref int[] _Array, int _First, int _Kind){
bool _Bool = false;
for (int _i = _Array.Length; _i > _First; _i--){
_Bool = false;
for (int _j = _First; _j < _i; _j++){
switch(_Kind){
case 1:
// - 小 -> 大
if (_Array[_j] > _Array[_j + 1]){
SwapArray(ref _Array, _j, _j + 1);
_Bool = true;
}
break;
case 2:
// - 大 -> 小
if (_Array[_j] < _Array[_j + 1]){
SwapArray(ref _Array, _j, _j + 1);
_Bool = true;
}
break;
}
}
if (!_Bool)
break;
}
}
// - 快速排序
public static void QuickSortArray(ref int[] _Array, int _First = 0){
QuickSort(ref _Array, _First, _Array.Length - 1);
}
private static void QuickSort(ref int[] _Array, int _left, int _right){
if (_left < _right)
{
int middle = _Array[(_left + _right) / 2];
int i = _left - 1;
int j = _right + 1;
while (true)
{
while (_Array[++i] < middle) ;
while (_Array[--j] > middle) ;
if (i >= j)
break;
SwapArray(ref _Array, i, j);
}
QuickSort(ref _Array, _left, i - 1);
QuickSort(ref _Array, j + 1, _right);
}
}
// -
public static void SwapArray(ref int[] _Array, int _A, int _B){
int _Temp = 0;
_Temp = _Array[_A];
_Array[_A] = _Array[_B];
_Array[_B] = _Temp;
}
// - 網路找到文字換行
public static string WarpWord(string originalWord,int lineWidth){
StringBuilder sb = new StringBuilder();
Regex punctuationRegex = new Regex(@"[,。;?~!:‘“”’【】()]");
int tempNum = 0; char[] c = originalWord.ToCharArray();
for (int i = 0; i < c.Length;i++){
if (c[i] >= 0x4e00 && c[i] <= 0x9fa5){
tempNum += 2;
if(tempNum>lineWidth){
i--;
sb.Append("\n");
tempNum = 0;
}else{
sb.Append(c[i]);
}
}else{
if (punctuationRegex.IsMatch(c[i].ToString())){
tempNum += 2;
if(tempNum>lineWidth){
i--;
sb.Append("\n");
tempNum = 0;
}else{
sb.Append(c[i]);
}
}else{
tempNum++;
if(tempNum>lineWidth){
i--;
sb.Append("\n");
tempNum = 0;
}else{
sb.Append(c[i]);
}
}
}
}
return sb.ToString();
}
// - 用來接全部的Debug.log之後只要關這個地方就好了
public static void ShowDebugLog(string _Msg){
Debug.Log(_Msg);
}
}
using UnityEngine;
using System.Collections;
public class LoadAssets : BaseLoader {
public Transform testTrans;
// Use this for initialization
IEnumerator Start () {
yield return StartCoroutine(Initialize() );
yield return StartCoroutine(LoadCharacterPartFromAssetBundle(testTrans,"YoungMale","Hair", 0, 0) );
yield return StartCoroutine(LoadCharacterPartFromAssetBundle(testTrans,"YoungMale","Face", 0, 0) );
}
IEnumerator LoadCharacterPartFromAssetBundle(Transform parentTrans, string characterType, string partName, int partType, int materialType){
// Load AssetBindlePath and Name
string assetBundleObjectName = "Character/" + characterType + "/Prefabs/Prefab_" + partName + "_" + partType.ToString("00");
string assetBundleMaterialName = "Character/" + characterType+ "/Materials/Mat_" + partName + "_" + partType.ToString("00") + "_" + materialType.ToString("00");
string assetObjectName = "Prefab_" + partName + "_" + partType.ToString("00");
string assetMaterialName = "Mat_" + partName + "_" + partType.ToString("00") + "_" + materialType.ToString("00");
// Cache Load Data
GameObject m_LoadGameObject = null;
Material m_LoadMaterial = null;
// Load AssetBundle
yield return StartCoroutine(LoadGameObject ( assetBundleObjectName, assetObjectName, value => m_LoadGameObject = value) );
yield return StartCoroutine(LoadMaterial ( assetBundleMaterialName, assetMaterialName, value => m_LoadMaterial = value) );
// Set Object Info And Instantiate
m_LoadGameObject = Instantiate(m_LoadGameObject);
m_LoadGameObject.name = assetObjectName;
m_LoadGameObject.GetComponentInChildren<Renderer>().material = m_LoadMaterial;
// Set Object Transform
if (parentTrans != null){
m_LoadGameObject.transform.SetParent(parentTrans, false);
m_LoadGameObject.transform.localPosition = Vector3.zero;
}
// Unload AssetBundle
AssetBundleManager.UnloadAssetBundle(assetBundleObjectName);
AssetBundleManager.UnloadAssetBundle(assetBundleMaterialName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment