IEnumerator DownloadAssetBundle()
    {
        yield return StartCoroutine(AssetBundleManager.downloadAssetBundle(url, version));

        bundle = AssetBundleManager.getAssetBundle(url, version);

        if (bundle != null)
            AssetLoader.Instance.SetInfoText("Download Success.... ");
        else
            AssetLoader.Instance.SetInfoText("Download error please retry");

        GameObject obj = Instantiate(bundle.LoadAsset("ExampleObject"),Vector3.zero,Quaternion.identity) as GameObject;
        // Unload the AssetBundles compressed contents to conserve memory
        //Debug.Log(obj);
        bundle.Unload(false);
    }
Пример #2
0
    void Start()
    {
        m_cube = AssetBundle.LoadFromFile("C:\\Users\\yunsubaek_df\\Documents\\AssetBundleTest1\\AssetBundles\\Windows\\cube-bundle");

        cube_obj = (GameObject)m_cube.LoadAsset<GameObject>("Cube");
        GameObject.Instantiate(cube_obj,new Vector3(1,1,1),Quaternion.identity);
    }
 void OnAssetsLoadingComplete(AssetBundle a_assetsbundle, AssetsInfo a_assetsInfo)
 {
     TotalAssets++;
     GameObject loadedObject;
     loadedObject = Instantiate(a_assetsbundle.LoadAsset(a_assetsInfo.AssetName, typeof(GameObject))) as GameObject;
     loadedObject.SetActive(false);
     m_assetsGameObjlst.Add(loadedObject.GetComponent<AssetsData>());
     if (TotalAssets == GameManager.Instance.AllAssetsInfoList.Count)
     {
       GameState l_gameState =  FiniteStateMachine.Instance.GetCurrentState<GameState>();
         l_gameState.MakeActiveArCameraAndImageTarget(m_assetsGameObjlst);
     }
 }
Пример #4
0
        /// <summary>
        /// Loads an asset by path (e.g. "assets/workspace/villager.prefab")
        /// </summary>
        /// <typeparam name="T">The type of the asset (e.g. GameObject or Sprite)</typeparam>
        /// <param name="path">The path of the asset</param>
        /// <returns></returns>
        public T GetAsset <T>(string path) where T : UnityEngine.Object
        {
            if (assets.ContainsKey(path))
            {
                return(assets[path] as T);
            }
            var asset = assetBundle?.LoadAsset <T>(path);

            if (asset != null)
            {
                assets[path] = asset;
            }
            return(asset);
        }
Пример #5
0
	public IEnumerator LoadManifest()
	{
		WWW manifest = new WWW (manifestPath);

		yield return manifest;

		if (!string.IsNullOrEmpty (manifest.error)) {
			Debug.Log (manifest.error);
		} else {
			if (manifest.progress >= 1.0f) {
				manifestLoader = manifest.assetBundle;

				assetManifest = manifestLoader.LoadAsset ("AssetBundleManifest") as AssetBundleManifest;

				IsLoadFinish = true;
			}
		}
	}
Пример #6
0
    IEnumerator LoadZombie(int index)
    {
        string bundleName = string.Format("myzombie{0}", index);
        string assetName = string.Format("myzombie{0}", index);
        string url = string.Format("file://{0}/{1}/{2}", Application.dataPath, bundlePath, bundleName);

        WWW www = WWW.LoadFromCacheOrDownload(url, 0);
        yield return www;

        if(!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError(www.error);
            return false;
        }

        downloadedAB = www.assetBundle;
        if (downloadedAB == null)
        {
            Debug.LogError("can't load assetbundle");
            return false;
        }

        /*
        Object[] objs = downloadedAB.LoadAllAssets();
        foreach(Object o in objs)
        {
            Debug.Log(string.Format("object name: {0}", o.name));
        }
        */

        Object obj = downloadedAB.LoadAsset(assetName);
        GameObject inst = Instantiate(obj) as GameObject;
        if (inst == null)
        {
            return false;
        }
        Debug.Log ("Prefab| instanceID: " + inst.GetInstanceID ());
        Debug.Log ("Prefab| Animator instanceID: " + inst.GetComponent<Animator> ().GetInstanceID ());
        Debug.Log ("Prefab| Avatar instanceID: " + inst.GetComponent<Animator> ().avatar.GetInstanceID ());
        Debug.Log ("---------------------------------------------------");
        //inst.transform.parent = gameObject.transform.parent;
        inst.transform.position = Vector3.zero;
        //downloadedAB.Unload (false);
    }
Пример #7
0
    public async static void LoadXMLByBundleAsync(string xmlName, string bundleName, string bundleDirectory, Action <XmlReader> callBack)
    {
        lock (callBackPool_XR)
        {
            if (callBackPool_XR.ContainsKey(xmlName))
            {
                return;
            }
            callBackPool_XR[xmlName] = callBack;
        }
        //LoadAssetBundleFromLocalAsync(bundleName, bundleDirectory);
        AssetBundle ab        = LoadAssetBundleFromLocal(bundleName, bundleDirectory);
        XmlReader   xr        = null;
        TextAsset   textAsset = ab?.LoadAsset <TextAsset>(xmlName);

        if (null != textAsset)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments   = true;
            settings.IgnoreWhitespace = true;
            settings.Async            = true;
            TextReader textReader = new StringReader(textAsset.text);
            xr = XmlReader.Create(textReader, settings);
        }
        else
        {
            Utils.LogError("null == textAsset, xmlName: " + xmlName);
            return;
        }
        await System.Threading.Tasks.Task.Run(async() =>
        {
            await Task.Delay(1);
            lock (callBackPool_XR)
            {
                if (callBackPool_XR.ContainsKey(xmlName))
                {
                    callBackPool_XR[xmlName](xr);
                }
                callBackPool_XR[xmlName] = null;
            }
        });
    }
        public AudioClip LoadVoiceAsset(string assetName)
        {
            int    _index = assetName.IndexOf('_');
            string script = assetName.Substring(0, _index);
            string number = assetName.Substring(_index + 1);

            Debug.Log($"LoadVoiceAsset. scriptName: {script}, number: {number}");
            AssetBundle ab   = voiceAssetBundleResManager.Get(script);
            AudioClip   clip = ab?.LoadAsset <AudioClip>(assetName);

            if (clip != null && clip.LoadAudioData())
            {
                Debug.Log("音频已成功加载");
                return(clip);
            }
            else
            {
                Debug.LogError("音效加载失败");
                return(null);
            }
        }
        public static GameObject GetPrefabs(string prefabName)
        {
            try
            {
                QuickLogger.Info($"Trying to find prefab ID: {prefabName}");
                if (!_init)
                {
                    QuickLogger.Debug($"AssetBundle Set");

                    QuickLogger.Debug("GetPrefabs");
                    _assetBundle = AssetHelper.Asset(Mod.ModName, Mod.BundleName);
                    _init        = true;
                }


                //We have found the asset bundle and now we are going to continue by looking for the model.
                GameObject prefab = _assetBundle?.LoadAsset <GameObject>(prefabName);



                //If the prefab isn't null lets add the shader to the materials
                if (prefab != null)
                {
                    //Lets apply the material shader
                    ApplyShaders(prefab, _assetBundle);
                    QuickLogger.Debug($"{prefabName} Found!");
                    return(prefab);
                }
                else
                {
                    QuickLogger.Error($"{prefabName} Not Found!");
                    return(null);
                }
            }
            catch (Exception e)
            {
                QuickLogger.Error <FCSDemoBuidable>(e.Message);
                return(null);
            }
        }
Пример #10
0
	// Use this for initialization
	void Start () {
		string assetsBundlePath = Application.streamingAssetsPath + "/bundle/";

		if(bundle != null)
			bundle.Unload(false);
		bundle = AssetBundle.LoadFromFile(assetsBundlePath + "bundle");

		string[] allAssetNames = bundle.GetAllAssetNames();
		foreach(var assetName in allAssetNames){
			print("AssetName: " + assetName);
			AssetBundleManifest assetBundleManifest = bundle.LoadAsset(assetName) as AssetBundleManifest;
			string[] allAssetBundles = assetBundleManifest.GetAllAssetBundles();
			foreach(var assetBundle in allAssetBundles){
				print("AssetBundleName: " + assetBundle);
				bundle = AssetBundle.LoadFromFile(assetsBundlePath + assetBundle);
				GameObject go = bundle.LoadAsset(assetBundle) as GameObject;
				Instantiate(go);
			}

		}

	}
Пример #11
0
        public IEnumerator PrepareDownload(string url, string manifestName)
        {
            // NOTE(JJO): url이 비어있다면 EDITOR모드임을 가정함.
            if (string.IsNullOrEmpty(url))
            {
                state = STATE.LOADED;
                yield break;
            }

            state = STATE.PREPARING;

            downloadUrl = url;

            // TODO(JJO): StreamingAssets에서 로드한 흔적을 찾는다.
            string manifestSA     = null;
            string manifestRemote = null;

            var pathSA = Path.Combine(Application.streamingAssetsPath, "Bundle");
            var path   = Path.Combine(pathSA, $"{manifestName}.manifest");

            using (var request = UnityWebRequest.Get(path))
            {
                yield return(request.SendWebRequest());

                if (string.IsNullOrEmpty(request.error) == false)
                {
                    Debug.LogWarning($"[AssetBundleManager|PrepareDownload] {manifestName} is NOT FOUND from StreamingAssets");
                }
                else
                {
                    manifestSA = request.downloadHandler.text;
                }
            }

            path = $"{downloadUrl}{manifestName}.manifest";
            using (var request = UnityWebRequest.Get(path))
            {
                yield return(request.SendWebRequest());

                if (string.IsNullOrEmpty(request.error) == false)
                {
                    Debug.LogError($"[AssetBundleManager|PrepareDownload] Failed to download - {path}\nReason: {request.error}");
                    state = STATE.ERROR;
                    yield break;
                }

                manifestRemote = request.downloadHandler.text;
            }

            if (string.IsNullOrEmpty(manifestSA) == false &&
                manifestSA == manifestRemote)
            {
                // NOTE(JJO): 그냥 여기에서 바로 S.A로부터 로드해버리자.
                path = Path.Combine(pathSA, manifestName);
                var request = AssetBundle.LoadFromFileAsync(path);

                yield return(request);

                _assetBundleManifestObject = request.assetBundle;
                if (_assetBundleManifestObject == null)
                {
                    Debug.LogError($"[AssetBundleManager|PrepareDownload] Failed to load - {path}\nReason: Unknown");
                    state = STATE.ERROR;
                    yield break;
                }

                _assetBundleManifest = _assetBundleManifestObject.LoadAsset <AssetBundleManifest>(nameof(AssetBundleManifest));

                var assetList = _assetBundleManifest.GetAllAssetBundles();
                var listCount = assetList.Length;
                for (int i = 0; i < listCount; ++i)
                {
                    path    = Path.Combine(pathSA, assetList[i]);
                    request = AssetBundle.LoadFromFileAsync(path);

                    yield return(request);

                    var bundle = request.assetBundle;
                    if (bundle == null)
                    {
                        Debug.LogError($"[AssetBundleManager|PrepareDownload] Failed to load - {path}\nReason: Unknown");
                        state = STATE.ERROR;
                        yield break;
                    }

                    _assetBundleList.Add(assetList[i], bundle);
                    Debug.Log($"[AssetBundleManager|PrepareDownload] Preload from StreamingAssets - {assetList[i]}");
                }
            }
            else
            {
                path = $"{downloadUrl}{manifestName}";
                using (var req = UnityWebRequestAssetBundle.GetAssetBundle(path))
                {
                    yield return(req.SendWebRequest());

                    if (string.IsNullOrEmpty(req.error) == false)
                    {
                        Debug.LogError($"[AssetBundleManager|PrepareDownload] Failed to download - {path}\nReason: Unknown");
                        state = STATE.ERROR;
                        yield break;
                    }

                    _assetBundleManifestObject = DownloadHandlerAssetBundle.GetContent(req);
                    _assetBundleManifest       = _assetBundleManifestObject.LoadAsset <AssetBundleManifest>(nameof(AssetBundleManifest));
                }

                var assetList = _assetBundleManifest.GetAllAssetBundles();
                var listCount = assetList.Length;
                for (int i = 0; i < listCount; ++i)
                {
                    path = Path.Combine(pathSA, $"{assetList[i]}.manifest");
                    using (var req = UnityWebRequest.Get(path))
                    {
                        yield return(req.SendWebRequest());

                        // NOTE(JJO): StreamingAssets에 파일이 없다면 바로 다운로드 리스트에 추가함.
                        if (string.IsNullOrEmpty(req.error))
                        {
                            manifestSA = req.downloadHandler.text;
                        }
                    }

                    path = $"{downloadUrl}{assetList[i]}.manifest";
                    using (var req = UnityWebRequest.Get(path))
                    {
                        yield return(req.SendWebRequest());

                        if (string.IsNullOrEmpty(req.error) == false)
                        {
                            Debug.LogError($"[AssetBundleManager|PrepareDownload] Network Error - {assetList[i]}\n{req.error}");
                            state = STATE.ERROR;
                            yield break;
                        }

                        manifestRemote = req.downloadHandler.text;
                    }

                    // NOTE(JJO): Manifest가 다르다면 다운로드 리스트에 추가함.
                    if (string.IsNullOrEmpty(manifestSA) ||
                        manifestSA != manifestRemote)
                    {
                        _downloadingAssetBundleList.Add(assetList[i], GetCRC(manifestRemote));
                    }
                    else
                    {
                        path = Path.Combine(pathSA, assetList[i]);
                        var request = AssetBundle.LoadFromFileAsync(path);

                        yield return(request);

                        var bundle = request.assetBundle;
                        if (bundle == null)
                        {
                            Debug.LogError($"[AssetBundleManager|PrepareDownload] {assetList[i]} NOT FOUND!");
                            state = STATE.ERROR;
                            yield break;
                        }

                        _assetBundleList.Add(assetList[i], bundle);
                        Debug.Log($"[AssetBundleManager|PrepareDownload] Preload from StreamingAssets - {assetList[i]}");
                    }
                }

                maximumAssetBundleCount = _downloadingAssetBundleList.Count;
            }
        }
Пример #12
0
    public static GameObject LoadAsset(AssetBundle bundle, string name)
    {
#if UNITY_5
        return bundle.LoadAsset(name, typeof(GameObject)) as GameObject;
#else
        return bundle.Load(name, typeof(GameObject)) as GameObject;
#endif
    }
Пример #13
0
        private async UniTask <AnimationGroup> LoadClipsAsync()
        {
            if (_asyncLoadInfo != null)
            {
                return(await ReturnExistingAsync());
            }

            AsyncLoadInfo <AnimationGroup> info = null;

            lock (this) {
                if (_asyncLoadInfo == null)
                {
                    info           = new AsyncLoadInfo <AnimationGroup>();
                    _asyncLoadInfo = info;
                }
            }

            if (info == null)
            {
                return(await ReturnExistingAsync());
            }

            var songResourceName = commonResourceProperties.danceResourceName;

            if (string.IsNullOrWhiteSpace(songResourceName))
            {
                info.Fail();
                throw new FormatException("Song resource name is empty.");
            }

            if (placement.motionNumber < MltdSimulationConstants.MinDanceMotion || placement.motionNumber > MltdSimulationConstants.MaxDanceMotion)
            {
                info.Fail();
                throw new FormatException($"Invalid motion number: {placement.motionNumber}, should be {MltdSimulationConstants.MinDanceMotion} to {MltdSimulationConstants.MaxDanceMotion}.");
            }

            if (placement.formationNumber < MltdSimulationConstants.MinDanceFormation || placement.motionNumber > MltdSimulationConstants.MaxDanceFormation)
            {
                info.Fail();
                throw new FormatException($"Invalid formation number: {placement.motionNumber}, should be {MltdSimulationConstants.MinDanceFormation} to {MltdSimulationConstants.MaxDanceFormation}.");
            }

            var danceAssetName = $"dan_{songResourceName}_{placement.motionNumber:00}";

            if (!DanceAssetNameRegex.IsMatch(danceAssetName))
            {
                info.Fail();
                throw new FormatException($"\"{danceAssetName}\" is not a valid dance asset name.");
            }

            var mainDanceBundle = await bundleLoader.LoadFromRelativePathAsync($"{danceAssetName}.imo.unity3d");

            AssetBundle appealBundle      = null;
            bool?       appealBundleFound = null;

            AnimationClip mainDance;

            {
                var assetPath  = $"assets/imas/resources/exclude/imo/dance/{songResourceName}/{danceAssetName}_dan.imo.asset";
                var motionData = mainDanceBundle.LoadAsset <CharacterImasMotionAsset>(assetPath);

                mainDance = await DanceAnimation.CreateAsync(motionData, danceAssetName);
            }

            async UniTask <AnimationClip> LoadAppealMotionAsync(string postfix)
            {
                var appealAssetName = $"dan_{songResourceName}_{placement.formationNumber:00}";

                AnimationClip result;
                var           assetPath = $"assets/imas/resources/exclude/imo/dance/{songResourceName}/{appealAssetName}_{postfix}.imo.asset";

                if (mainDanceBundle.Contains(assetPath))
                {
                    var motionData = mainDanceBundle.LoadAsset <CharacterImasMotionAsset>(assetPath);
                    result = await DanceAnimation.CreateAsync(motionData, $"{appealAssetName}_{postfix}");
                }
                else
                {
                    if (appealBundleFound.HasValue)
                    {
                        if (!appealBundleFound.Value)
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        bool found;
                        (appealBundle, found) = await TryLoadExternalAppealBundleAsync();

                        appealBundleFound = found;
                    }

                    if (appealBundle != null && appealBundle.Contains(assetPath))
                    {
                        var motionData = appealBundle.LoadAsset <CharacterImasMotionAsset>(assetPath);
                        result = await DanceAnimation.CreateAsync(motionData, $"{appealAssetName}_{postfix}");
                    }
                    else
                    {
                        result = null;
                    }
                }

                return(result);
            }

            var specialAppeal = await LoadAppealMotionAsync("apg");

            var anotherAppeal = await LoadAppealMotionAsync("apa");

            var gorgeousAppeal = await LoadAppealMotionAsync("bpg");

            var animationGroup = new AnimationGroup(mainDance, specialAppeal, anotherAppeal, gorgeousAppeal);

            info.Success(animationGroup);

            return(animationGroup);
        }
Пример #14
0
    IEnumerator LoadZombieModel()
    {
        string bundleName = "zombie_model";
        string assetName = "zombie";
        string url = string.Format("file://{0}/{1}/{2}", Application.dataPath, bundlePath, bundleName);

        WWW www = WWW.LoadFromCacheOrDownload(url, 0);
        yield return www;

        if(!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError(www.error);
            return false;
        }

        downloadedAB = www.assetBundle;
        if (downloadedAB == null)
        {
            Debug.LogError("can't load assetbundle");
            return false;
        }

        loadedModel_ = downloadedAB.LoadAsset (assetName) as GameObject;
        Debug.Log ("Model| instanceID: " + loadedModel_.GetInstanceID ());
        Debug.Log ("Model| Animator instanceID: " + loadedModel_.GetComponent<Animator> ().GetInstanceID ());
        Debug.Log ("Model| Avatar instanceID: " + loadedModel_.GetComponent<Animator> ().avatar.GetInstanceID ());
        Debug.Log ("---------------------------------------------------");

        //downloadedAB.LoadAsset (assetName);
    }
Пример #15
0
    //--------------COROUTINES-----------------------------------
    /* LoadConf()
     * Chargement de la configuration d'abri par défaut
     **/
    private IEnumerator LoadConf()
    {
        _isBuilding = true;
        Montage.assetBundleLock = true;
        //Attend que le objdata soit configuré
        while(gameObject.GetComponent<ObjData>()==null)
        {
                yield return new WaitForEndOfFrame();
        }
            while(gameObject.GetComponent<ObjData>().GetObjectModel() == null)
            {
                yield return new WaitForEndOfFrame();
            }
        _lib = GetComponent<ObjData>().GetObjectModel().GetLibrary();
        //Récupération de l'assetbundle
        //		OSLib libObj = GetComponent<ObjData>().GetObjectModel().GetLibrary();
        WWW www = WWW.LoadFromCacheOrDownload (_lib.GetAssetBundlePath (), _lib.GetVersion ());
        yield return www;

        if (www.error != null)
        {
            Debug.Log ("AssetBundle ERROR" + www.error);
        }
        else
        {
            _assetBundle = www.assetBundle;
            if (_assetBundle != null)
            {
                //Chargement de la config
                TextAsset confXml = _assetBundle.LoadAsset (modelName+"_conf", typeof (TextAsset)) as TextAsset;
                if (confXml != null)
                {
                    _dsMdl.ParseConfFile(confXml);
                }

            }
            _assetBundle.Unload (false);
        }
        www.Dispose();

        //Création de l'abri par default
        ArrayList stConf= _dsMdl.GetdefaultConf();
        _currentColor = _dsMdl.GetColor(_currentColorIndex);

        if(stConf.Count > 0)
        {
        //			SaveTransform();
            _hasFacadeInDefaultBegin = false;
            _hasFacadeInDefaultEnd = false;
            for(int i=0;i<stConf.Count;i=i+3)
            {
                ModuleType typ = ModuleType.bloc;
                switch ((string)stConf[i])
                {
                case "facade":
                    typ = ModuleType.facade;
                    break;
                case "bloc":
                    typ = ModuleType.bloc;
                    if(IsAbrifixe())
                    {
                        typ = ModuleType.multiBloc;
                    }
                    break;
                case "extremite":
                    typ = ModuleType.extremite;
                    break;
                case "multibloc":
                    typ = ModuleType.multiBloc;
                    break;
                }

                if((typ == ModuleType.facade) && (i==0))
                {
                    _hasFacadeInDefaultBegin = true;
                    _saveTailleBegin = (int) stConf[i+1];
                    _saveStyleBegin = (string) stConf[i+2];
                    continue;
                }
                if((typ == ModuleType.facade) && (i>0))
                {
                    _hasFacadeInDefaultEnd = true;
                    _saveTailleEnd = (int) stConf[i+1];
                    _saveStyleEnd = (string) stConf[i+2];
                    continue;
                }

                int t = (int) stConf[i+1];

                string styl = (string) stConf[i+2];

                _nextInsertion = true;
                _decalZ = 0.0f;
                yield return StartCoroutine(AddModule(t,styl,typ,/*_dsMdl.GetColor(0)*/_currentColor,true));

            }

            _isBuilding = false;
        }
        if(!_hasFacadeInDefaultEnd)
        {
            _selectedIndex = 0;
            if(IsAbrifixe())
                _selectedIndex = Mathf.Clamp(_selectedIndex,1,_modules.Count-2);
        }
        UpdateCurrentModule();
        UpdateModules();
        UpdateBoxCollider();
        ChangeModuleColor(_currentColor);

        //	www.Dispose();
        Montage.assetBundleLock = false;
        enabled = false;

        if(_hasFacadeInDefaultEnd)
        {
            yield return StartCoroutine(AddModule(_saveTailleEnd,_saveStyleEnd,ModuleType.facade,_currentColor,true));
            _hasFacadeInDefaultEnd = false;
            _selectedIndex = 0;
            if(IsAbrifixe())
                _selectedIndex = Mathf.Clamp(_selectedIndex,1,_modules.Count-2);

        }

        if(_hasFacadeInDefaultBegin)
        {
            _selectedIndex = 0;
            UpdateCurrentModule();
            _nextInsertion = false;
            yield return StartCoroutine(AddModule(_saveTailleBegin,_saveStyleBegin,ModuleType.facade,_currentColor,true));
            _hasFacadeInDefaultBegin = false;
            if(IsAbrifixe())
                _selectedIndex = Mathf.Clamp(_selectedIndex,1,_modules.Count-2);

            UpdateCurrentModule();
            UpdateModules();
            UpdateBoxCollider();
        }

        //CenterDeployAndFeetLimit();

        yield return null;
    }
Пример #16
0
        private static Shader LoadShader(string shaderName, string assetBundlePath, string assetPath)
        {
            Shader shader = null;

            if (assetBundlePath.IsNullOrEmpty())
            {
                return(shader);
            }
            else
            {
                if (assetPath.IsNullOrEmpty())
                {
                    try
                    {
                        if (assetBundlePath.StartsWith("Resources."))
                        {
                            AssetBundle bundle = AssetBundle.LoadFromMemory(UILib.Resource.LoadEmbeddedResource($"{nameof(KK_Plugins)}.{assetBundlePath}"));
                            shader = bundle.LoadAsset <Shader>(shaderName);
                            bundle.Unload(false);
                            return(shader);
                        }
                        else
                        {
                            return(CommonLib.LoadAsset <Shader>(assetBundlePath, $"{shaderName}"));
                        }
                    }
                    catch
                    {
                        Logger.LogWarning($"Unable to load shader: {shaderName}");
                        return(null);
                    }
                }
                else
                {
                    try
                    {
                        if (assetBundlePath.StartsWith("Resources."))
                        {
                            AssetBundle bundle = AssetBundle.LoadFromMemory(UILib.Resource.LoadEmbeddedResource($"{nameof(KK_Plugins)}.{assetBundlePath}"));
                            shader = bundle.LoadAsset <Shader>(shaderName);
                            var go = bundle.LoadAsset <GameObject>(assetPath);
                            bundle.Unload(false);

                            if (shader == null)
                            {
                                var renderers = go.GetComponentsInChildren <Renderer>();
                                for (var i = 0; i < renderers.Length; i++)
                                {
                                    var renderer = renderers[i];
                                    for (var j = 0; j < renderer.materials.Length; j++)
                                    {
                                        var material = renderer.materials[j];
                                        if (material.shader.NameFormatted() == shaderName)
                                        {
                                            shader = material.shader;
                                        }
                                    }
                                }
                            }
                            Destroy(go);

                            return(shader);
                        }
                        else
                        {
#if PH
                            AssetBundle bundle = AssetBundle.LoadFromFile(assetBundlePath);
                            var         go     = bundle.LoadAsset <GameObject>(assetPath);
                            bundle.Unload(false);
#else
                            var go = CommonLib.LoadAsset <GameObject>(assetBundlePath, assetPath);
#endif
                            var renderers = go.GetComponentsInChildren <Renderer>();
                            for (var i = 0; i < renderers.Length; i++)
                            {
                                var renderer = renderers[i];
                                for (var j = 0; j < renderer.materials.Length; j++)
                                {
                                    var material = renderer.materials[j];
                                    if (material.shader.NameFormatted() == shaderName)
                                    {
                                        shader = material.shader;
                                    }
                                }
                            }
                            Destroy(go);
                            return(shader);
                        }
                    }
                    catch
                    {
                        Logger.LogWarning($"Unable to load shader: {shaderName}");
                        return(shader);
                    }
                }
            }
        }
 public UnityEngine.Video.VideoClip LoadVideoAsset(string assetName)
 {
     return(videoAssetBundle?.LoadAsset <UnityEngine.Video.VideoClip>(assetName));
 }
Пример #18
0
    void InstanceSpineGo()
    {
        UnityEngine.Profiling.Profiler.BeginSample("MyPieceOfCode 111");
        Debug.Log("111111111");
        UnityEngine.Profiling.Profiler.EndSample();

        LoadSceneMgr loadSceneMgr = GameObject.FindObjectOfType <LoadSceneMgr>();

        Canvas            canvas          = GameObject.FindObjectOfType <Canvas>();
        AssetBundle       ab              = null;
        float             preTime         = 0.0f;
        string            prefabAssetPath = "";
        Object            prefab          = null;
        GameObject        go;
        List <GameObject> goList = new List <GameObject>();

        preTime         = Time.realtimeSinceStartup;
        ab              = loadSceneMgr.LoadBundle("binary_SkeletonGraphic");
        prefabAssetPath = "Assets/res/Prefabs/binary_SkeletonGraphic.prefab";
        prefab          = ab.LoadAsset <Object>(prefabAssetPath);
        Debug.Log(string.Format(" {0} Load Bundle Time : {1} ", "binary_SkeletonGraphic",
                                Time.realtimeSinceStartup - preTime));


        preTime = Time.realtimeSinceStartup;
        go      = Instantiate(prefab) as GameObject;

        Debug.Log(string.Format(" {0} Instantiate Time : {1} ", "binary_SkeletonGraphic",
                                Time.realtimeSinceStartup - preTime));

        go.transform.SetParent(canvas.transform, false);


        UnityEngine.Profiling.Profiler.BeginSample("MyPieceOfCode 222");
        Debug.Log("222222");
        UnityEngine.Profiling.Profiler.EndSample();

        /*
         * LoadSceneMgr loadSceneMgr = GameObject.FindObjectOfType<LoadSceneMgr>();
         *
         * Canvas canvas = GameObject.FindObjectOfType<Canvas>();
         * AssetBundle ab = null;
         * float preTime = 0.0f;
         * string prefabAssetPath = "";
         * Object prefab = null;
         * GameObject go;
         * List<GameObject> goList = new List<GameObject>();
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * ab = loadSceneMgr.LoadBundle("binary_SkeletonGraphic");
         * prefabAssetPath = "Assets/res/Prefabs/binary_SkeletonGraphic.prefab";
         * prefab = ab.LoadAsset<Object>(prefabAssetPath);
         * Debug.Log(string.Format(" {0} Load Bundle Time : {1} ", "binary_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * go = Instantiate(prefab) as GameObject;
         *
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList.Add(Instantiate(prefab) as GameObject);
         * //}
         *
         * Debug.Log(string.Format(" {0} Instantiate Time : {1} ", "binary_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         *
         * go.transform.SetParent(canvas.transform, false);
         *
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList[i].transform.SetParent(canvas.transform, false);
         * //}
         *
         *
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * ab = loadSceneMgr.LoadBundle("json_SkeletonGraphic");
         * prefabAssetPath = "Assets/res/Prefabs/json_SkeletonGraphic.prefab";
         * prefab = ab.LoadAsset<Object>(prefabAssetPath);
         * Debug.Log(string.Format(" {0} Load Bundle Time : {1} ", "json_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * go = Instantiate(prefab) as GameObject;
         * //goList = new List<GameObject>();
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList.Add(Instantiate(prefab) as GameObject);
         * //}
         * Debug.Log(string.Format(" {0} Instantiate Time : {1} ", "json_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         * go.transform.SetParent(canvas.transform, false);
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList[i].transform.SetParent(canvas.transform, false);
         * //}
         *
         */
    }
    /**
     * date 2019.08.19
     * author Day
     * desc
     *  위에 GetObjectFromFolder 형식을 맞춤
     *  GetAssetBundle 에서 AssetBundle 을 가져옴
     *  AssetBundleManifest 에 저장 되어 있는 경로를 이용해 객체를 가져오는 방식
     */
    IEnumerator GetObjectFromFolder_Bundle()
    {
        string localPath = dir_path + "/AssetBundles/";

        for (int i = 1; i <= 5; i++)
        {
            string bundleName = "";

            switch (i)
            {
            case 1: bundleName = "items"; break;

            case 2: bundleName = "human"; break;

            case 3: bundleName = "place"; break;

            case 4: bundleName = "wall"; break;

            case 5: bundleName = "handitem"; break;
            }

            //- Assets/Resources/Item/Human/3dObject/Daughter.prefab

            yield return(StartCoroutine(AssetBundlePatch.Instance.LoadAssetBundle(localPath, bundleName + ".unity3d", false)));

            AssetBundle ab = AssetBundlePatch.Instance.GetAssetBundle(localPath, bundleName + ".unity3d");

            string[] bundlePath = ab.GetAllAssetNames();

            int pathLength;
            int nameLength;

            foreach (string path in bundlePath)
            {
                string[] extension = path.Split('.');
                //Debug.Log(extension[0] + " + " + extension[1]);

                string[] obj = extension[0].Split('/');
                //Debug.Log(obj[0] + " + " + obj[1] + " + " + obj[2] + " + " + obj[3] + " + " + obj[4] + " + " + obj[5]);

                string[] objName = obj[5].Split('_');

                pathLength = obj.Length;
                nameLength = objName.Length;

                if (i == 2 || i == 5)
                {
                    nameLength += 1;
                }

                if ((pathLength == 6) && (nameLength == 3))
                {
                    Debug.Log(bundleName + " : " + obj[5]);
                    int giving_OriginNumber = Convert.ToInt32(objName[0]);

                    if (extension[1].Equals("prefab"))
                    {
                        Item       tmp    = null;
                        GameObject tmpobj = ab.LoadAsset <GameObject>(obj[5]);

                        if (!_itemsTable.ContainsKey(bundleName))
                        {
                            Dictionary <int, Item> _ii = new Dictionary <int, Item>();

                            _itemsTable.Add(bundleName, _ii);
                        }
                        if (!_itemsTable[bundleName].ContainsKey(giving_OriginNumber))
                        {
                            if (tmpobj != null)
                            {
                                switch (i)
                                {
                                case 1: tmp = AddItem(obj[5], giving_OriginNumber, tmpobj); break;

                                case 2: tmp = AddHuman(obj[5], giving_OriginNumber, tmpobj); break;

                                case 3: tmp = AddPlace(obj[5], giving_OriginNumber, tmpobj); break;

                                case 4: tmp = AddWall(obj[5], giving_OriginNumber, tmpobj); break;

                                case 5: tmp = AddHandItem(obj[5], giving_OriginNumber, tmpobj); break;
                                }

                                _itemsTable[bundleName].Add(giving_OriginNumber, tmp);
                            }
                        }
                    }
                    else if (extension[1].Equals("png"))
                    {
                        Sprite tmpspr = ab.LoadAsset <Sprite>(obj[5]);

                        if (!_itemsImages.ContainsKey(bundleName))
                        {
                            Dictionary <int, Sprite> _is = new Dictionary <int, Sprite>();

                            _itemsImages.Add(bundleName, _is);
                        }
                        if (!_itemsImages[bundleName].ContainsKey(giving_OriginNumber))
                        {
                            if (tmpspr != null)
                            {
                                _itemsImages[bundleName].Add(giving_OriginNumber, tmpspr);
                                Debug.Log("Images_save_check");
                            }
                        }
                    }
                }
            }
        }
    }
Пример #20
0
        // Token: 0x06000192 RID: 402 RVA: 0x0000CD0C File Offset: 0x0000AF0C
        public static void Add()
        {
            Gun gun = ETGMod.Databases.Items.NewGun("Bubbler", "bubbler");

            Game.Items.Rename("outdated_gun_mods:bubbler", "bb:bubbler");
            gun.gameObject.AddComponent <Bubbler>();
            GunExt.SetShortDescription(gun, "A Bleaker Blaster");
            GunExt.SetLongDescription(gun, "A strange gun that seems to pulse at a steady rate. As you hold the gun, the pulse finds its way into your every move...\n\nLet's dance.");
            GunExt.SetupSprite(gun, null, "bubbler_idle_001", 10);
            tk2dSpriteAnimationClip fireClip = gun.sprite.spriteAnimator.GetClipByName("bubbler_fire");

            fireClip.wrapMode  = tk2dSpriteAnimationClip.WrapMode.LoopSection;
            fireClip.loopStart = 1;
            GunExt.SetAnimationFPS(gun, gun.reloadAnimation, 10);
            GunExt.SetAnimationFPS(gun, gun.shootAnimation, 10);
            GunExt.SetAnimationFPS(gun, gun.idleAnimation, 10);
            GunExt.AddProjectileModuleFrom(gun, PickupObjectDatabase.GetById(36) as Gun, true, false);
            gun.DefaultModule.ammoCost      = 1;
            gun.DefaultModule.shootStyle    = ProjectileModule.ShootStyle.Automatic;
            gun.DefaultModule.sequenceStyle = ProjectileModule.ProjectileSequenceStyle.Random;
            gun.reloadTime = 2f;
            gun.DefaultModule.cooldownTime        = 0.125f;
            gun.DefaultModule.numberOfShotsInClip = 16;
            gun.barrelOffset.position            += new Vector3(0.8f, 0f, 0f);
            gun.SetBaseMaxAmmo(500);
            gun.InfiniteAmmo = true;
            gun.quality      = PickupObject.ItemQuality.SPECIAL;
            gun.encounterTrackable.EncounterGuid = "627562626c65";
            Projectile projectile = UnityEngine.Object.Instantiate <Projectile>(gun.DefaultModule.projectiles[0]);

            projectile.gameObject.SetActive(false);
            FakePrefab.MarkAsFakePrefab(projectile.gameObject);
            UnityEngine.Object.DontDestroyOnLoad(projectile);
            gun.DefaultModule.projectiles[0] = projectile;
            projectile.baseData.damage       = 4f;
            projectile.transform.parent      = gun.barrelOffset;
            Projectile bubbleProjectile = UnityEngine.Object.Instantiate <Projectile>(gun.DefaultModule.projectiles[0]);

            bubbleProjectile.gameObject.SetActive(false);
            FakePrefab.MarkAsFakePrefab(bubbleProjectile.gameObject);
            UnityEngine.Object.DontDestroyOnLoad(bubbleProjectile);
            bubbleProjectile.transform.parent = gun.barrelOffset;
            bubbleProjectile.SetProjectileSpriteRight("bubbler_projectile", 16, 16);
            bubbleProjectile.baseData.speed  *= 0.5f;
            bubbleProjectile.baseData.damage *= 3f;
            gun.DefaultModule.usesOptionalFinalProjectile = true;
            gun.DefaultModule.numberOfFinalProjectiles    = 1;
            gun.DefaultModule.finalProjectile             = bubbleProjectile;
            gun.DefaultModule.finalAmmoType       = ((Gun)ETGMod.Databases.Items[599]).DefaultModule.ammoType;
            gun.DefaultModule.finalCustomAmmoType = ((Gun)ETGMod.Databases.Items[599]).DefaultModule.customAmmoType;
            ETGMod.Databases.Items.Add(gun, null, "ANY");
            Bubbler.goopDefs = new List <GoopDefinition>();
            AssetBundle assetBundle = ResourceManager.LoadAssetBundle("shared_auto_001");

            foreach (string text in Bubbler.goops)
            {
                GoopDefinition goopDefinition;
                try
                {
                    GameObject gameObject2 = assetBundle.LoadAsset(text) as GameObject;
                    goopDefinition = gameObject2.GetComponent <GoopDefinition>();
                }
                catch
                {
                    goopDefinition = (assetBundle.LoadAsset(text) as GoopDefinition);
                }
                goopDefinition.name = text.Replace("assets/data/goops/", "").Replace(".asset", "");
                Bubbler.goopDefs.Add(goopDefinition);
            }
        }
Пример #21
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="platform">平台</param>
        /// <param name="getFileCallback">获取资源真实路径回调</param>
        /// <param name="editor">是否使用AssetDataBase加载</param>
        /// <param name="offset">获取bundle的偏移</param>
        public void Initialize(string platform, Func <string, string> getFileCallback, bool editor, ulong offset)
        {
            m_Editor = editor;

            if (m_Editor)
            {
                return;
            }

            BundleManager.instance.Initialize(platform, getFileCallback, offset);

            string      manifestBunldeFile  = getFileCallback.Invoke(MANIFEST_BUNDLE);
            AssetBundle manifestAssetBundle = AssetBundle.LoadFromFile(manifestBunldeFile, 0, offset);

            TextAsset resourceTextAsset   = manifestAssetBundle.LoadAsset(RESOURCE_ASSET_NAME) as TextAsset;
            TextAsset bundleTextAsset     = manifestAssetBundle.LoadAsset(BUNDLE_ASSET_NAME) as TextAsset;
            TextAsset dependencyTextAsset = manifestAssetBundle.LoadAsset(DEPENDENCY_ASSET_NAME) as TextAsset;

            byte[] resourceBytes   = resourceTextAsset.bytes;
            byte[] bundleBytes     = bundleTextAsset.bytes;
            byte[] dependencyBytes = dependencyTextAsset.bytes;

            manifestAssetBundle.Unload(true);
            manifestAssetBundle = null;

            //保存id对应的asseturl
            Dictionary <ushort, string> assetUrlDic = new Dictionary <ushort, string>();

            #region 读取资源信息
            {
                MemoryStream resourceMemoryStream = new MemoryStream(resourceBytes);
                BinaryReader resourceBinaryReader = new BinaryReader(resourceMemoryStream);
                //获取资源个数
                ushort resourceCount = resourceBinaryReader.ReadUInt16();
                for (ushort i = 0; i < resourceCount; i++)
                {
                    string assetUrl = resourceBinaryReader.ReadString();
                    assetUrlDic.Add(i, assetUrl);
                }
            }
            #endregion

            #region 读取bundle信息
            {
                ResourceBunldeDic.Clear();
                MemoryStream bundleMemoryStream = new MemoryStream(bundleBytes);
                BinaryReader bundleBinaryReader = new BinaryReader(bundleMemoryStream);
                //获取bundle个数
                ushort bundleCount = bundleBinaryReader.ReadUInt16();
                for (int i = 0; i < bundleCount; i++)
                {
                    string bundleUrl = bundleBinaryReader.ReadString();
                    //string bundleFileUrl = getFileCallback(bundleUrl);
                    string bundleFileUrl = bundleUrl;
                    //获取bundle内的资源个数
                    ushort resourceCount = bundleBinaryReader.ReadUInt16();
                    for (int ii = 0; ii < resourceCount; ii++)
                    {
                        ushort assetId  = bundleBinaryReader.ReadUInt16();
                        string assetUrl = assetUrlDic[assetId];
                        ResourceBunldeDic.Add(assetUrl, bundleFileUrl);
                    }
                }
            }
            #endregion

            #region 读取资源依赖信息
            {
                ResourceDependencyDic.Clear();
                MemoryStream dependencyMemoryStream = new MemoryStream(dependencyBytes);
                BinaryReader dependencyBinaryReader = new BinaryReader(dependencyMemoryStream);
                //获取依赖链个数
                ushort dependencyCount = dependencyBinaryReader.ReadUInt16();
                for (int i = 0; i < dependencyCount; i++)
                {
                    //获取资源个数
                    ushort        resourceCount  = dependencyBinaryReader.ReadUInt16();
                    ushort        assetId        = dependencyBinaryReader.ReadUInt16();
                    string        assetUrl       = assetUrlDic[assetId];
                    List <string> dependencyList = new List <string>(resourceCount);
                    for (int ii = 1; ii < resourceCount; ii++)
                    {
                        ushort dependencyAssetId = dependencyBinaryReader.ReadUInt16();
                        string dependencyUrl     = assetUrlDic[dependencyAssetId];
                        dependencyList.Add(dependencyUrl);
                    }

                    ResourceDependencyDic.Add(assetUrl, dependencyList);
                }
            }
            #endregion
        }
Пример #22
0
        public IEnumerator PrepareDownload(string url, string manifestName, string assetBundleDirectoryName)
        {
            state = STATE.PREPARING;

            downloadUrl          = url;
            localAssetBundlePath = Path.Combine(Application.persistentDataPath, assetBundleDirectoryName);
            if (Directory.Exists(localAssetBundlePath) == false)
            {
                Directory.CreateDirectory(localAssetBundlePath);
            }

            var    localManifestRawPath = Path.Combine(localAssetBundlePath, $"{manifestName}.manifest");
            var    localManifestPath    = Path.Combine(localAssetBundlePath, manifestName);
            string localManifestRaw     = string.Empty;
            string remoteManifestRaw    = string.Empty;

            // NOTE(JJO): 로컬에 저장된 데이터가 없다면 StreamingAssets를 검사하여 모든 StreamingAssets의 AssetBundle을 가져옴
            if (File.Exists(localManifestRawPath) == false)
            {
                var streamingAssetsPath = Path.Combine(Application.streamingAssetsPath, "Bundle");
                if (Directory.Exists(streamingAssetsPath))
                {
                    var fileList      = Directory.GetFiles(streamingAssetsPath);
                    var fileListCount = fileList.Length;
                    for (int i = 0; i < fileListCount; ++i)
                    {
                        if (fileList[i].Contains(".meta"))
                        {
                            continue;
                        }

                        var fileName        = Path.GetFileName(fileList[i]);
                        var destinationPath = Path.Combine(localAssetBundlePath, fileName);
                        File.Copy(fileList[i], destinationPath);
                        Debug.Log($"[PrepareDownload] Copy {fileList[i]} to {destinationPath}");
                    }
                }
            }

            // NOTE(JJO): 다시 로컬에 있는지 검사하여 가져옴
            if (File.Exists(localManifestRawPath))
            {
                localManifestRaw = File.ReadAllText(localManifestRawPath);
            }

            var remoteManifestRawPath = downloadUrl.EndsWith("/") == false ? $"{downloadUrl}/{manifestName}.manifest" : $"{downloadUrl}{manifestName}.manifest";

            using (var request = UnityWebRequest.Get(remoteManifestRawPath))
            {
                yield return(request.SendWebRequest());

                if (string.IsNullOrEmpty(request.error) == false)
                {
                    Debug.LogError($"[PrepareDownload] Failed to load a manifest from {remoteManifestRawPath}\n{request.error}");
                    state = STATE.ERROR;
                    yield break;
                }

                remoteManifestRaw = request.downloadHandler.text;
            }

            if (string.IsNullOrEmpty(localManifestRaw) ||
                localManifestRaw != remoteManifestRaw)
            {
                // NOTE(JJO): 먼저 AssetBundleManifest를 받아서 정보를 가져옴.
                var remoteManifestPath = downloadUrl.EndsWith("/") == false ? $"{downloadUrl}/{manifestName}" : $"{downloadUrl}{manifestName}";

                using (var request = UnityWebRequest.Get(remoteManifestPath))
                {
                    yield return(request.SendWebRequest());

                    if (request.isNetworkError ||
                        request.isHttpError ||
                        string.IsNullOrEmpty(request.error) == false)
                    {
                        Debug.LogError($"[PrepareDownload] Failed to load a manifest from {remoteManifestPath}\n{request.error}");
                        state = STATE.ERROR;
                        yield break;
                    }

                    _assetBundleManifestObject = AssetBundle.LoadFromMemory(request.downloadHandler.data, 0);

                    File.WriteAllBytes(localManifestPath, request.downloadHandler.data);

                    // NOTE(JJO): Manifest 쓰기가 완료되고 나서 txt도 쓴다.
                    File.WriteAllText(localManifestRawPath, remoteManifestRaw);
                }
            }
            else
            {
                _assetBundleManifestObject = AssetBundle.LoadFromFile(localManifestPath);
            }

            _assetBundleManifest = _assetBundleManifestObject.LoadAsset <AssetBundleManifest>(MANIFEST_NAME);

            maximumAssetBundleCount = _assetBundleManifest.GetAllAssetBundles().Length;

            var localAssetBundleFileNameList = Directory.GetFiles(localAssetBundlePath).ToList();
            var assetList = _assetBundleManifest.GetAllAssetBundles();
            var listCount = assetList.Length;

            // NOTE(JJO): 쓰지 않는 AssetBundle 제거
            if (localAssetBundleFileNameList.Count > 0)
            {
                for (var assetIndex = 0; assetIndex < listCount; ++assetIndex)
                {
                    var localAssetBundleFileNameListCount = localAssetBundleFileNameList.Count;
                    for (var fileIndex = localAssetBundleFileNameListCount - 1; fileIndex >= 0; --fileIndex)
                    {
                        var fileName = Path.GetFileName(localAssetBundleFileNameList[fileIndex]);
                        if (fileName == manifestName ||
                            fileName == $"{manifestName}.manifest" ||
                            fileName == assetList[assetIndex] ||
                            fileName == $"{assetList[assetIndex]}.manifest")
                        {
                            localAssetBundleFileNameList.RemoveAt(fileIndex);
                        }
                    }
                }
            }

            if (localAssetBundleFileNameList.Count > 0)
            {
                var localAssetBundleFileNameListCount = localAssetBundleFileNameList.Count;
                for (var fileIndex = localAssetBundleFileNameListCount - 1; fileIndex >= 0; --fileIndex)
                {
                    File.Delete(localAssetBundleFileNameList[fileIndex]);
                }
            }

            // NOTE(JJO): 받아야하는 에셋의 크기를 계산한다!
            assetBundleTotalSize = 0;
            for (int i = 0; i < listCount; ++i)
            {
                var downloadPath = downloadUrl.EndsWith("/") == false ? $"{downloadUrl}/{assetList[i]}" : $"{downloadUrl}{assetList[i]}";
                remoteManifestRawPath = $"{downloadPath}.manifest";
                remoteManifestRaw     = string.Empty;
                localManifestRawPath  = Path.Combine(localAssetBundlePath, $"{assetList[i]}.manifest");
                if (File.Exists(localManifestRawPath))
                {
                    localManifestRaw = File.ReadAllText(localManifestRawPath);
                }
                else
                {
                    localManifestRaw = string.Empty;
                }

                using (var request = UnityWebRequest.Get(remoteManifestRawPath))
                {
                    yield return(request.SendWebRequest());

                    if (string.IsNullOrEmpty(request.error) == false)
                    {
                        Debug.LogError($"[PrepareDownload] Failed to download a {assetList[i]}.manifest from {remoteManifestRawPath}!\n{request.error}");
                        state = STATE.ERROR;
                        yield break;
                    }

                    remoteManifestRaw = request.downloadHandler.text;
                }

                if (string.IsNullOrEmpty(localManifestRaw) ||
                    localManifestRaw != remoteManifestRaw)
                {
                    // NOTE(JJO): 받아야 하는 에셋의 크기를 구한다.
                    using (var request = UnityWebRequest.Head(downloadPath))
                    {
                        yield return(request.SendWebRequest());

                        if (request.isNetworkError ||
                            request.isHttpError)
                        {
                            Debug.LogError($"[PrepareDownload] Failed to get size of a {assetList[i]} from {downloadPath}!\n{request.error}");
                            state = STATE.ERROR;
                            yield break;
                        }

                        ulong assetBundleSize;
                        ulong.TryParse(request.GetResponseHeader(CONTENT_LENGTH), out assetBundleSize);
                        assetBundleTotalSize += assetBundleSize;

                        _downloadingAssetBundleList.Add(assetList[i], GetCRC(remoteManifestRaw));
                    }
                }
            }
        }
Пример #23
0
 /// <summary>
 /// 同步加载资源;
 /// </summary>
 /// <param name="varAssetName">资源名</param>
 /// <returns></returns>
 public UnityEngine.Object LoadAsset(string varAssetName)
 {
     AddAssetRefTree(varAssetName);
     return(mAssetBundle.LoadAsset(varAssetName));
 }
Пример #24
0
        internal object GetItemAsset(PackageItem item)
        {
            switch (item.type)
            {
            case PackageItemType.Image:
                if (!item.decoded)
                {
                    item.decoded = true;
                    AtlasSprite sprite;
                    if (_sprites.TryGetValue(item.id, out sprite))
                    {
                        item.texture = CreateSpriteTexture(sprite);
                    }
                    else
                    {
                        item.texture = NTexture.Empty;
                    }
                }
                return(item.texture);

            case PackageItemType.Atlas:
                if (!item.decoded)
                {
                    item.decoded = true;
                    string fileName = string.IsNullOrEmpty(item.file) ? (item.id + ".png") : item.file;
                    string filePath = _assetNamePrefix + Path.GetFileNameWithoutExtension(fileName);
                    string ext      = Path.GetExtension(fileName);

                    Texture2D tex;
                    if (_resBundle != null)
                    {
#if UNITY_5
                        tex = _resBundle.LoadAsset <Texture2D>(filePath);
#else
                        tex = (Texture2D)_resBundle.Load(filePath, typeof(Texture2D));
#endif
                    }
                    else
                    {
                        tex = (Texture2D)_loadFunc(filePath, ext, typeof(Texture2D));
                    }
                    if (tex == null)
                    {
                        Debug.LogWarning("FairyGUI: texture '" + fileName + "' not found in " + this.name);
                        item.texture = NTexture.Empty;
                    }
                    else
                    {
                        if (tex.mipmapCount > 1)
                        {
                            Debug.LogWarning("FairyGUI: texture '" + fileName + "' in " + this.name + " is mipmaps enabled.");
                        }
                        item.texture             = new NTexture(tex, (float)tex.width / item.width, (float)tex.height / item.height);
                        item.texture.storedODisk = _resBundle == null;

                        filePath = filePath + "!a";
                        if (_resBundle != null)
                        {
#if UNITY_5
                            tex = _resBundle.LoadAsset <Texture2D>(filePath);
#else
                            tex = (Texture2D)_resBundle.Load(filePath, typeof(Texture2D));
#endif
                        }
                        else
                        {
                            tex = (Texture2D)_loadFunc(filePath, ext, typeof(Texture2D));
                        }
                        if (tex != null)
                        {
                            item.texture.alphaTexture             = new NTexture(tex);
                            item.texture.alphaTexture.storedODisk = _resBundle == null;
                        }
                    }
                }
                return(item.texture);

            case PackageItemType.Sound:
                if (!item.decoded)
                {
                    item.decoded = true;
                    string fileName = _assetNamePrefix + Path.GetFileNameWithoutExtension(item.file);
                    string ext      = Path.GetExtension(item.file);
                    if (_resBundle != null)
                    {
#if UNITY_5
                        item.audioClip = _resBundle.LoadAsset <AudioClip>(fileName);
#else
                        item.audioClip = (AudioClip)_resBundle.Load(fileName, typeof(AudioClip));
#endif
                    }
                    else
                    {
                        item.audioClip = (AudioClip)_loadFunc(fileName, ext, typeof(AudioClip));
                    }
                }
                return(item.audioClip);

            case PackageItemType.Font:
                if (!item.decoded)
                {
                    item.decoded = true;
                    LoadFont(item);
                }
                return(item.bitmapFont);

            case PackageItemType.MovieClip:
                if (!item.decoded)
                {
                    item.decoded = true;
                    LoadMovieClip(item);
                }
                return(item.frames);

            case PackageItemType.Component:
                if (!item.decoded)
                {
                    item.decoded = true;
                    string str = _descPack[item.id + ".xml"];
                    XML    xml = new XML(str);
                    if (_stringsSource != null)
                    {
                        Dictionary <string, string> strings;
                        if (_stringsSource.TryGetValue(this.id + item.id, out strings))
                        {
                            TranslateComponent(xml, strings);
                        }
                    }
                    item.componentData = xml;
                }
                return(item.componentData);

            default:
                if (!item.decoded)
                {
                    item.decoded = true;
                    item.binary  = LoadBinary(item.file);
                }
                return(item.binary);
            }
        }
Пример #25
0
        static void SetupScene(SimulationModel simulation)
        {
            Dictionary <string, GameObject> cachedVehicles = new Dictionary <string, GameObject>();

            using (var db = DatabaseManager.Open())
            {
                try
                {
                    foreach (var agentConfig in Instance.SimConfig.Agents)
                    {
                        var         bundlePath    = agentConfig.AssetBundle;
                        AssetBundle textureBundle = null;
                        AssetBundle vehicleBundle = null;
                        if (cachedVehicles.ContainsKey(agentConfig.Name))
                        {
                            agentConfig.Prefab = cachedVehicles[agentConfig.Name];
                            continue;
                        }

                        using (ZipFile zip = new ZipFile(bundlePath))
                        {
                            Manifest manifest;
                            ZipEntry entry = zip.GetEntry("manifest");
                            using (var ms = zip.GetInputStream(entry))
                            {
                                int    streamSize = (int)entry.Size;
                                byte[] buffer     = new byte[streamSize];
                                streamSize = ms.Read(buffer, 0, streamSize);

                                try
                                {
                                    manifest = new Deserializer().Deserialize <Manifest>(Encoding.UTF8.GetString(buffer, 0, streamSize));
                                }
                                catch
                                {
                                    throw new Exception("Out of date AssetBundle, rebuild or download latest AssetBundle.");
                                }
                            }

                            if (manifest.bundleFormat != BundleConfig.Versions[BundleConfig.BundleTypes.Vehicle])
                            {
                                zip.Close();

                                // TODO: proper exception
                                throw new ZipException("BundleFormat version mismatch");
                            }

                            var texStream = zip.GetInputStream(zip.GetEntry($"{manifest.assetGuid}_vehicle_textures"));
                            textureBundle = AssetBundle.LoadFromStream(texStream, 0, 1 << 20);

                            string platform  = SystemInfo.operatingSystemFamily == OperatingSystemFamily.Windows ? "windows" : "linux";
                            var    mapStream = zip.GetInputStream(zip.GetEntry($"{manifest.assetGuid}_vehicle_main_{platform}"));

                            vehicleBundle = AssetBundle.LoadFromStream(mapStream, 0, 1 << 20);

                            if (vehicleBundle == null)
                            {
                                throw new Exception($"Failed to load '{agentConfig.Name}' vehicle asset bundle");
                            }

                            try
                            {
                                var vehicleAssets = vehicleBundle.GetAllAssetNames();
                                if (vehicleAssets.Length != 1)
                                {
                                    throw new Exception($"Unsupported '{agentConfig.Name}' vehicle asset bundle, only 1 asset expected");
                                }

                                if (manifest.fmuName != "")
                                {
                                    var fmuDirectory = Path.Combine(Application.persistentDataPath, manifest.assetName);
                                    if (platform == "windows")
                                    {
                                        var dll = zip.GetEntry($"{manifest.fmuName}_windows.dll");
                                        if (dll == null)
                                        {
                                            throw new ArgumentException($"{manifest.fmuName}.dll not found in Zip {bundlePath}");
                                        }

                                        using (Stream s = zip.GetInputStream(dll))
                                        {
                                            byte[] buffer = new byte[4096];
                                            Directory.CreateDirectory(fmuDirectory);
                                            var path = Path.Combine(Application.persistentDataPath, manifest.assetName, $"{manifest.fmuName}.dll");
                                            using (FileStream streamWriter = File.Create(path))
                                            {
                                                StreamUtils.Copy(s, streamWriter, buffer);
                                            }
                                            vehicleBundle.LoadAsset <GameObject>(vehicleAssets[0]).GetComponent <VehicleFMU>().FMUData.Path = path;
                                        }
                                    }
                                    else
                                    {
                                        var dll = zip.GetEntry($"{manifest.fmuName}_linux.so");
                                        if (dll == null)
                                        {
                                            throw new ArgumentException($"{manifest.fmuName}.so not found in Zip {bundlePath}");
                                        }

                                        using (Stream s = zip.GetInputStream(dll))
                                        {
                                            byte[] buffer = new byte[4096];
                                            Directory.CreateDirectory(fmuDirectory);
                                            var path = Path.Combine(Application.persistentDataPath, manifest.assetName, $"{manifest.fmuName}.so");
                                            using (FileStream streamWriter = File.Create(path))
                                            {
                                                StreamUtils.Copy(s, streamWriter, buffer);
                                            }
                                            vehicleBundle.LoadAsset <GameObject>(vehicleAssets[0]).GetComponent <VehicleFMU>().FMUData.Path = path;
                                        }
                                    }
                                }

                                // TODO: make this async
                                if (!AssetBundle.GetAllLoadedAssetBundles().Contains(textureBundle))
                                {
                                    textureBundle?.LoadAllAssets();
                                }

                                agentConfig.Prefab = vehicleBundle.LoadAsset <GameObject>(vehicleAssets[0]);
                                cachedVehicles.Add(agentConfig.Name, agentConfig.Prefab);
                            }
                            finally
                            {
                                textureBundle?.Unload(false);
                                vehicleBundle.Unload(false);
                            }
                        }
                    }

                    var sim = CreateSimulatorManager();
                    if (simulation.Seed != null)
                    {
                        sim.Init(simulation.Seed);
                    }
                    else
                    {
                        sim.Init();
                    }

                    Instance.CurrentSimulation        = simulation;
                    Instance.CurrentSimulation.Status = "Running";
                    // Notify WebUI simulation is running
                    NotificationManager.SendNotification("simulation",
                                                         SimulationResponse.Create(Loader.Instance.CurrentSimulation),
                                                         Loader.Instance.CurrentSimulation.Owner);

                    if (Instance.SimConfig.Clusters.Length == 0)
                    {
                        // Flash main window to let user know simulation is ready
                        WindowFlasher.Flash();
                    }
                    else
                    {
                        Instance.Network.Master.InitializeSimulation(sim.gameObject);
                    }
                }
                catch (ZipException ex)
                {
                    Debug.Log($"Failed to start '{simulation.Name}' simulation - out of date asset bundles");
                    Debug.LogException(ex);

                    // NOTE: In case of failure we have to update Simulation state
                    simulation.Status = "Invalid";
                    simulation.Error  = "Out of date Vehicle AssetBundle. Please check content website for updated bundle or rebuild the bundle.";
                    db.Update(simulation);

                    // TODO: take ex.Message and append it to response here
                    NotificationManager.SendNotification("simulation", SimulationResponse.Create(simulation), simulation.Owner);

                    ResetLoaderScene();
                }
                catch (Exception ex)
                {
                    Debug.Log($"Failed to start '{simulation.Name}' simulation");
                    Debug.LogException(ex);

                    // NOTE: In case of failure we have to update Simulation state
                    simulation.Status = "Invalid";
                    simulation.Error  = ex.Message;
                    db.Update(simulation);

                    // TODO: take ex.Message and append it to response here
                    NotificationManager.SendNotification("simulation", SimulationResponse.Create(simulation), simulation.Owner);

                    ResetLoaderScene();
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Will retrieve asset either from LoadedAssets or asset bundle and return it. Will load
        /// asset bundle if necessary.
        /// </summary>
        /// <typeparam name="T">Type of asset</typeparam>
        /// <param name="assetName">name of asset</param>
        /// <param name="loadedBundle">had to load asset bundle</param>
        /// <returns>A reference to the loaded asset or null if not found.</returns>
        private T LoadAssetFromBundle <T>(string assetName, out bool loadedBundle) where T : UnityEngine.Object
        {
            LoadedAsset la = new LoadedAsset();

            loadedBundle = false;

            if (string.IsNullOrEmpty(assetName))
            {
                return(null);
            }
            try
            {
                assetName = ModManager.GetAssetName(assetName);
                float time = Time.realtimeSinceStartup;

                if (IsAssetLoaded(assetName))
                {
                    la = loadedAssets[assetName];
                    if (la.Obj)
                    {
                        // Update timestamp of last access, but only if difference is
                        // significant to limit the number of reassignment to dictionary.
                        if (la.TimeStamp < 0 || time - la.TimeStamp > 59)
                        {
                            la.TimeStamp            = time;
                            loadedAssets[assetName] = la;
                        }

                        return(la.Obj as T);
                    }

                    loadedAssets.Remove(assetName);
                    Debug.LogWarningFormat("Removed asset {0} from cache of mod {1} because object is unloaded.", assetName, Title);
                }

#if UNITY_EDITOR
                if (IsVirtual)
                {
                    la.Obj = LoadAssetFromResources <T>(assetName);
                    if (la.Obj != null)
                    {
                        la.T         = la.Obj.GetType();
                        la.TimeStamp = time;
                        loadedAssets.Add(assetName, la);
                    }
                    return(la.Obj as T);
                }
#endif

                if (AssetBundle == null)
                {
                    loadedBundle = LoadAssetBundle();
                }

                if (AssetBundle.Contains(assetName))
                {
                    la.Obj = AssetBundle.LoadAsset <T>(assetName);

                    if (la.Obj != null)
                    {
                        la.T         = la.Obj.GetType();
                        la.TimeStamp = time;
                        AddAsset(assetName, la);
                    }
                    return(la.Obj as T);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.Message);
                return(null);
            }
        }
Пример #27
0
 public static Object LoadAsset(string name)
 {
     return(AssetBundle.LoadAsset(name));
 }
Пример #28
0
        public static void Init(AssetBundle expandSharedAssets1)
        {
            Gun pistol = ETGMod.Databases.Items.NewGun("Bootleg Pistol", "bootleg_pistol");

            Game.Items.Rename("outdated_gun_mods:bootleg_pistol", "ex:bootleg_pistol");
            pistol.SetShortDescription("Of questionable quality...");
            pistol.SetLongDescription("It's a counterfeit gun.\n\nDue to low quality standards, this weapon may be prone to exploding under certain circumstances...");
            GunExt.SetupSprite(pistol, null, "bootleg_pistol_idle_001", 18);
            pistol.AddProjectileModuleFrom("Magnum", true, false);
            pistol.barrelOffset.localPosition -= new Vector3(0.3f, 0.2f, 0);
            pistol.DefaultModule.ammoCost      = 1;
            pistol.PreventOutlines             = true;
            pistol.reloadTime = 1;
            pistol.gunClass   = GunClass.PISTOL;
            pistol.ammo       = 140;
            pistol.SetBaseMaxAmmo(140);
            pistol.quality = ItemQuality.D;
            if (!ExpandSettings.EnableEXItems)
            {
                pistol.quality = ItemQuality.EXCLUDED;
            }
            pistol.UsesCustomCost = true;
            pistol.CustomCost     = 10;
            pistol.encounterTrackable.EncounterGuid = "baad9dd6d005458daf02933f6a1ba926";
            pistol.gameObject.AddComponent <ExpandRemoveGunOnAmmoDepletion>();
            pistol.gameObject.AddComponent <ExpandMaybeLoseAmmoOnDamage>();
            ETGMod.Databases.Items.Add(pistol);
            BootlegPistolID = pistol.PickupObjectId;

            PistolProjectile = expandSharedAssets1.LoadAsset <GameObject>("EXBootlegPistolProjectile");
            tk2dSprite           PistolProjectileSprite    = SpriteSerializer.AddSpriteToObject(PistolProjectile.transform.Find("Sprite").gameObject, ExpandPrefabs.EXGunCollection, "bootleg_pistol_projectile_001");
            SpeculativeRigidbody pistolProjectileRigidBody = PistolProjectile.AddComponent <SpeculativeRigidbody>();

            ExpandUtility.DuplicateRigidBody(pistolProjectileRigidBody, pistol.DefaultModule.projectiles[0].specRigidbody);
            Projectile PistolProjectileComponent = PistolProjectile.AddComponent <Projectile>();

            ExpandUtility.DuplicateComponent(PistolProjectileComponent, pistol.DefaultModule.projectiles[0]);
            pistol.DefaultModule.projectiles[0] = PistolProjectileComponent;
            PistolProjectile.gameObject.transform.localPosition = pistol.barrelOffset.localPosition;


            Gun machinepistol = ETGMod.Databases.Items.NewGun("Bootleg Machine Pistol", "bootleg_machinepistol");

            Game.Items.Rename("outdated_gun_mods:bootleg_machine_pistol", "ex:bootleg_machine_pistol");
            machinepistol.SetShortDescription("Of questionable quality...");
            machinepistol.SetLongDescription("It's a counterfeit machine gun.\n\nDue to low quality standards, this weapon may be prone to exploding under certain circumstances...");
            GunExt.SetupSprite(machinepistol, null, "bootleg_machinepistol_idle_001", 30);
            machinepistol.AddProjectileModuleFrom(PickupObjectDatabase.GetById(43).name, true, false);
            machinepistol.barrelOffset.localPosition -= new Vector3(0.3f, 0.2f, 0);
            machinepistol.PreventOutlines             = true;
            machinepistol.reloadTime = 1.2f;
            machinepistol.gunClass   = GunClass.FULLAUTO;
            machinepistol.ammo       = 600;
            machinepistol.SetBaseMaxAmmo(600);
            machinepistol.quality = ItemQuality.D;
            if (!ExpandSettings.EnableEXItems)
            {
                machinepistol.quality = ItemQuality.EXCLUDED;
            }
            machinepistol.gunSwitchGroup = "Uzi";
            machinepistol.UsesCustomCost = true;
            machinepistol.CustomCost     = 15;
            machinepistol.encounterTrackable.EncounterGuid = "e56adda5081347e5b9e0cf2556689b0e";
            machinepistol.gameObject.AddComponent <ExpandRemoveGunOnAmmoDepletion>();
            machinepistol.gameObject.AddComponent <ExpandMaybeLoseAmmoOnDamage>();
            ETGMod.Databases.Items.Add(machinepistol);
            BootlegMachinePistolID = machinepistol.PickupObjectId;

            MachinePistolProjectile = expandSharedAssets1.LoadAsset <GameObject>("EXBootlegMachinePistolProjectile");
            tk2dSprite           MachinePistolProjectileSprite    = SpriteSerializer.AddSpriteToObject(MachinePistolProjectile.transform.Find("Sprite").gameObject, ExpandPrefabs.EXGunCollection, "bootleg_pistol_projectile_001");
            SpeculativeRigidbody machinePistolProjectileRigidBody = MachinePistolProjectile.AddComponent <SpeculativeRigidbody>();

            ExpandUtility.DuplicateRigidBody(machinePistolProjectileRigidBody, machinepistol.DefaultModule.projectiles[0].specRigidbody);
            Projectile MachinePistolProjectileComponent = MachinePistolProjectile.AddComponent <Projectile>();

            ExpandUtility.DuplicateComponent(MachinePistolProjectileComponent, machinepistol.DefaultModule.projectiles[0]);
            machinepistol.DefaultModule.projectiles[0] = MachinePistolProjectileComponent;
            MachinePistolProjectile.gameObject.transform.localPosition = machinepistol.barrelOffset.localPosition;


            Gun shotgun = ETGMod.Databases.Items.NewGun("Bootleg Shotgun", "bootleg_shotgun");

            Game.Items.Rename("outdated_gun_mods:bootleg_shotgun", "ex:bootleg_shotgun");
            shotgun.SetShortDescription("Of questionable quality...");
            shotgun.SetLongDescription("It's a counterfeit shotgun.\n\nDue to low quality standards, this weapon may be prone to exploding under certain circumstances...");
            GunExt.SetupSprite(shotgun, null, "bootleg_shotgun_idle_001", 18);
            shotgun.AddProjectileModuleFrom(PickupObjectDatabase.GetById(51).name, true, false);
            shotgun.barrelOffset.localPosition -= new Vector3(0.3f, 0.2f, 0);
            shotgun.PreventOutlines             = true;
            shotgun.reloadTime = 1.8f;
            shotgun.gunClass   = GunClass.SHOTGUN;
            shotgun.ammo       = 150;
            shotgun.SetBaseMaxAmmo(150);
            shotgun.quality = ItemQuality.D;
            if (!ExpandSettings.EnableEXItems)
            {
                shotgun.quality = ItemQuality.EXCLUDED;
            }
            shotgun.gunSwitchGroup = "Shotgun";
            shotgun.UsesCustomCost = true;
            shotgun.CustomCost     = 18;
            shotgun.encounterTrackable.EncounterGuid = "fa0575b4cf0140ddb6b0ed6d962bff47";
            shotgun.gameObject.AddComponent <ExpandRemoveGunOnAmmoDepletion>();
            shotgun.gameObject.AddComponent <ExpandMaybeLoseAmmoOnDamage>();
            ETGMod.Databases.Items.Add(shotgun);
            BootlegShotgunID = shotgun.PickupObjectId;

            ShotgunProjectile = expandSharedAssets1.LoadAsset <GameObject>("EXBootlegShotgunProjectile");
            tk2dSprite           ShotgunProjectileSprite    = SpriteSerializer.AddSpriteToObject(ShotgunProjectile.transform.Find("Sprite").gameObject, ExpandPrefabs.EXGunCollection, "bootleg_pistol_projectile_001");
            SpeculativeRigidbody ShotgunProjectileRigidBody = ShotgunProjectile.AddComponent <SpeculativeRigidbody>();

            ExpandUtility.DuplicateRigidBody(ShotgunProjectileRigidBody, shotgun.DefaultModule.projectiles[0].specRigidbody);
            Projectile ShotgunProjectileComponent = ShotgunProjectile.AddComponent <Projectile>();

            ExpandUtility.DuplicateComponent(ShotgunProjectileComponent, shotgun.DefaultModule.projectiles[0]);
            shotgun.DefaultModule.projectiles[0] = ShotgunProjectileComponent;
            ProjectileVolleyData shotgunVollyData = new ProjectileVolleyData()
            {
                projectiles = new List <ProjectileModule>()
                {
                    shotgun.DefaultModule,
                    new ProjectileModule(),
                    new ProjectileModule(),
                    new ProjectileModule(),
                    new ProjectileModule(),
                    new ProjectileModule(),
                },
                UsesBeamRotationLimiter      = false,
                BeamRotationDegreesPerSecond = 30,
                ModulesAreTiers = false,
                UsesShotgunStyleVelocityRandomizer = true,
                DecreaseFinalSpeedPercentMin       = -15,
                IncreaseFinalSpeedPercentMax       = 15
            };

            JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(shotgun.DefaultModule), shotgunVollyData.projectiles[1]);
            JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(shotgun.DefaultModule), shotgunVollyData.projectiles[2]);
            JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(shotgun.DefaultModule), shotgunVollyData.projectiles[3]);
            JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(shotgun.DefaultModule), shotgunVollyData.projectiles[4]);
            JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(shotgun.DefaultModule), shotgunVollyData.projectiles[5]);
            shotgunVollyData.projectiles[1].ammoType = GameUIAmmoType.AmmoType.SMALL_BULLET;
            shotgunVollyData.projectiles[2].ammoType = GameUIAmmoType.AmmoType.SMALL_BULLET;
            shotgunVollyData.projectiles[3].ammoType = GameUIAmmoType.AmmoType.SMALL_BULLET;
            shotgunVollyData.projectiles[4].ammoType = GameUIAmmoType.AmmoType.SMALL_BULLET;
            shotgunVollyData.projectiles[5].ammoType = GameUIAmmoType.AmmoType.SMALL_BULLET;
            shotgun.Volley = shotgunVollyData;
            ShotgunProjectileComponent.gameObject.transform.localPosition = shotgun.barrelOffset.localPosition;


            BootlegPistol        = pistol;
            BootlegMachinePistol = machinepistol;
            BootlegShotgun       = shotgun;
        }
Пример #29
0
    public IEnumerator AddModule(int size,string style,ModuleType typ,Color32 color,bool fromInit=false, bool bsensfacade=false)
    {
        //Debug.Log("t : "+size+", styl : "+style+",ModuleType : "+ typ.ToString()+", bool "+fromInit);

        bool noNeedLimitToBeRecalculate = fromInit;
        _isBuilding = true;
        //-------vv-Récupération du mesh-vv------------
        DynShelterModule newModule = null;
        string newStyle= string.Copy(style);
        string tag = CheckAndCreateTag(size,style,typ,out newStyle);
        style = string.Copy(newStyle);

        GameObject go = null;
        bool bextrem = false;

        //--vv--Si il na pas deja été créé, ben tant pis on ouvre--vv--
        if(go == null)
        {
        //			OSLib libObj = GetComponent<ObjData>().GetObjectModel().GetLibrary();
            WWW www = WWW.LoadFromCacheOrDownload (_lib.GetAssetBundlePath (), _lib.GetVersion ());
            yield return www;
            if (www.error != null)
            {
                Debug.Log ("AssetBundle ERROR" + www.error);
            }
            else
            {
                _assetBundle = www.assetBundle;
                if (_assetBundle != null)
                {
                    string sz = _assetBundle.name;

                    if(sz.Contains("extrem"))
                    {
                        bextrem = true;
                    }

                //	Debug.Log("assetBundle.load  : "+tag);
                    Object original = _assetBundle.LoadAsset (tag, typeof(GameObject));
                    if(original!=null){
                        go = (GameObject) Instantiate (original);
                    }
                    /*else
                    {

                        _assetBundle.Unload (false);
                        www.Dispose();
                    }*/

                }
                _assetBundle.Unload (false);
            }
            www.Dispose();
        }

        //-------vv-Création du module-vv---------------
        switch(typ)
        {
        case ModuleType.bloc:
            newModule = new DynShelterBloc(size,style,typ,color,this);
            break;
        case ModuleType.facade:
            noNeedLimitToBeRecalculate=true;
            newModule = new DynShelterFacade(size,style,typ,color,this);
            m_icounterFacade++;
            break;
        case ModuleType.extremite:
            newModule = new DynShelterExtrem(size,style,typ,color,this);
            break;
        case ModuleType.multiBloc:
            newModule = new DynShelterMultiBloc(size,style,ModuleType.bloc,color,this);
            if(_currentModule==null)
            {
                break;
            }
            if(_currentModule.GetType() == typeof(DynShelterBloc))
            {
                DynShelterMultiBloc newCurrent = new DynShelterMultiBloc((DynShelterBloc)_currentModule);
                foreach(DynShelterModule dm in _modules)
                {
                    if(dm.GetPrevModule() == _currentModule)
                        dm.SetPrevModule(newCurrent);
                    if(dm.GetNextModule() == _currentModule)
                        dm.SetNextModule(newCurrent);
                }

                _currentModule = newCurrent;
                _modules[_selectedIndex] = _currentModule;
            }
            else
            {
                if(_currentModule.GetPrevModule() != null)
                {
                    if(_currentModule.GetPrevModule().GetSize() == size && _currentModule.GetPrevModule().GetType() == typeof(DynShelterBloc))
                    {
                        Debug.Log("Modifying Prev");
                        DynShelterMultiBloc newPrev = new DynShelterMultiBloc((DynShelterBloc)_currentModule.GetPrevModule());
                        int idx = _modules.IndexOf(_currentModule.GetPrevModule());
                        _modules[idx] = newPrev;
                        _currentModule.SetNextModule(newPrev);
                    }
                }

                if(_currentModule.GetNextModule() != null)
                {
                    Debug.Log("Modifying Next");
                    if(_currentModule.GetNextModule().GetSize() == size && _currentModule.GetNextModule().GetType() == typeof(DynShelterBloc))
                    {
                        DynShelterMultiBloc newNext = new DynShelterMultiBloc((DynShelterBloc)_currentModule.GetNextModule());
                        int idx = _modules.IndexOf(_currentModule.GetNextModule());
                        _modules[idx] = newNext;
                        _currentModule.SetNextModule(newNext);
                    }
                }
            }
            break;
        }

        SaveTransform();
        go.transform.parent = transform;
        go.transform.localPosition = Vector3.zero;

        if(_currentModule != null)
        {
            if(bsensfacade && bextrem)
            {
                _currentModule.bextrem = true;
                go.transform.Rotate(0.0f, 180.0f, 0.0f);
            }
            else
            {
                _currentModule.bextrem = false;
            }
        }

        newModule.SetGameObject(go);
        _modManager.TestModuleForGlobalMods(go);

        //-------vv-Placement-vv-----------------------
        if(_currentModule != null)
        {
        //			Debug.Log(" _currentModule not null");
            if(_nextInsertion)
            {
        //				Debug.Log(" _nextInsertion");
                newModule.InsertBetween(_currentModule,_currentModule.GetNextModule());
                print ("_selectedIndex :"+ _selectedIndex );
                if( _selectedIndex+1 <= _modules.Count)
                {
                    _modules.Insert(_selectedIndex+1,newModule);
                    _selectedIndex++;
                }
            }
            else
            {
        //				Debug.Log("Not _nextInsertion");
            /*	if(_currentModule.GetType() == typeof(DynShelterMultiBloc)
                    && newModule.GetType() == typeof(DynShelterMultiBloc)
                    && _currentModule.GetPrevModule().GetType() == typeof(DynShelterFacade))
                {
                    newModule.InsertBetween(_currentModule,_currentModule.GetNextModule());
                    _modules.Insert(_selectedIndex+1,newModule);
                }
                else*/
                {
                    newModule.InsertBetween(_currentModule.GetPrevModule(),_currentModule);
                    _modules.Insert(_selectedIndex,newModule);
                }
            }

            //Déplacement Immobile ^^ QUICKFIX placement des facades a l'ajout de celles-ci
            _currentModule.MoveModuleV2(0,_currentModule,true,true);
        }
        else
        {
        //			Debug.Log(" _currentModule  null");
            newModule.SetPos(false,0);
            newModule.SetNextPrevModule(null,null);
            newModule.SetNextPrevLocks(true,true);
            _modules.Add(newModule);
            //_selectedIndex = 0;
        }
        UI.SetItemsNb(_modules.Count);
        UpdateCurrentModule();
        _removeModule = false;
        ChangeModuleColor(_currentColor);

        UpdateLimits(noNeedLimitToBeRecalculate);

        ReapplyTransform();

        if(szbrand == "PoolCover")
        {
            UpdateBoxCollider();
            UpdateVisibility();
        }

        //CenterDeployAndFeetLimit();

        yield return new WaitForEndOfFrame();
        _isBuilding = false;
    }
Пример #30
0
    private IEnumerator DownloadAssetBundle(string asset, string bundleName, int version)
    {
        loadedAsset = null;

        // Wait for the Caching system to be ready
        while (!Caching.ready)
        {
            yield return null;
        }

        string url = baseURL + bundleName;

        // Start the download
        using (WWW www = WWW.LoadFromCacheOrDownload(url, version))
        {
            yield return www;
            if (www.error != null)
            {
                throw new System.Exception("AssetBundle - WWW download:" + www.error);
            }
            thisAssetBundle = www.assetBundle;

            //load the specified asset into memory
            loadedAsset = thisAssetBundle.LoadAsset(asset, typeof(GameObject));

            www.Dispose();

            isDone = true;
        }
    }
Пример #31
0
    /* ChangeModuleStyle(int idx)
     * Changement de style d'un module par le idx ième
     * */
    public IEnumerator ChangeModuleStyle(int idx, bool bsensfacade=false)
    {
        string newStyle = _tmpStylesNames[idx];
        string newTag = _currentModule.GetModuleType().ToString()+"_t"+_currentModule.GetSize()+"_"+newStyle;
        if(newStyle != _currentModule.GetStyle())
        {
            //Récupére le GameObject du nouveau style
            GameObject go = null;
            bool bextrem = false;
            //--vv--Copie un module éxistant pour éviter de réouvrir l'assetBundle--vv--
        //			foreach(DynShelterModule dsMod in _modules)
        //			{
        //				if(dsMod.GetTag() == newTag)
        //				{
        //					go = (GameObject)Instantiate(dsMod.GetGameObj());
        //					break;
        //				}
        //			}

            //--vv--Si il na pas deja été créé, ben tant pis on ouvre--vv--
        //			if(go == null)
        //			{
        //				OSLib libObj = GetComponent<ObjData>().GetObjectModel().GetLibrary();
                WWW www = WWW.LoadFromCacheOrDownload (_lib.GetAssetBundlePath (), _lib.GetVersion ());
                yield return www;
                if (www.error != null)
                {
                    Debug.Log ("AssetBundle ERROR" + www.error);
                }
                else
                {
                    _assetBundle = www.assetBundle;
                    if (_assetBundle != null)
                    {

                    string sz = newTag;
                        if(sz.Contains("extrem"))
                        {
                            bextrem = true;
                        }

                        Debug.Log("assetBundle.load  : "+newTag);
                        Object original = _assetBundle.LoadAsset (newTag, typeof(GameObject));

                        go = (GameObject) Instantiate (original);
                    }
                    _assetBundle.Unload (false);
                }
                www.Dispose();
        //			}
            SaveTransform();
            go.transform.parent = transform;
            go.transform.localRotation = _currentModule.GetGameObj().transform.localRotation;//Quaternion.identity;
            go.transform.localScale = Vector3.one;

            if(bextrem)
            {
                if(bsensfacade)
                {
                    go.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);
                    //go.transform.Rotate(0.0f, 180.0f, 0.0f);
                }

                _currentModule.bextrem = true;
            }
            else
            {
                _currentModule.bextrem = false;
            }

            if(!IsAbrifixe())
            {
                go.transform.localPosition = _currentModule.GetPos();
                _modManager.TestModuleForGlobalMods(go);
                _modManager.RemoveModFrom(_currentModule.GetGameObj());
                Destroy(_currentModule.GetGameObj());
                _currentModule.ChangeStyle(newStyle,go);
                _modules[_selectedIndex] = _currentModule;
                //ChangeModuleColor(_currentColor);
            }
            else
            {
                int curMod=0;
                //foreach(DynShelterModule m in _modules)
                for(int modulIndex=0;modulIndex<_modules.Count;modulIndex++)
                {
                    DynShelterModule m = (DynShelterModule) _modules[modulIndex];
                    if(m.GetModuleType()==_currentModule.GetModuleType())
                    {
                        GameObject goCopy = (GameObject)Instantiate(go);
                        goCopy.transform.parent = transform;
                        goCopy.transform.localPosition = m.GetPos();
                        _modManager.TestModuleForGlobalMods(goCopy);
                        _modManager.RemoveModFrom(m.GetGameObj());
                        Destroy(m.GetGameObj());
                        m.ChangeStyle(newStyle,goCopy);
                        _modules[modulIndex] = m;
                    }
                    curMod++;
                }
                Destroy(go);
            }

            ChangeModuleColor(_currentColor);
            ReapplyTransform();
        }
        yield return null;
    }
Пример #32
0
    private static bool TransferSceneBundles(OVRADBTool adbTool, string absoluteTempPath, string externalSceneCache)
    {
        List <string> bundlesToTransfer = new List <string>();
        List <string> bundlesToDelete   = new List <string>();
        string        manifestFilePath  = externalSceneCache + "/" + BUNDLE_MANAGER_MASTER_BUNDLE;

        string[] pullManifestCommand = { "-d pull", "\"" + manifestFilePath + "\"", "\"" + absoluteTempPath + "\"" };

        string output, error;

        if (adbTool.RunCommand(pullManifestCommand, null, out output, out error) == 0)
        {
            // An existing manifest file was found on device. Load hashes and upload bundles that have changed hashes.
            Debug.Log("[OVRBundleManager] - Scene bundle manifest file found. Decoding changes . . .");

            // Load hashes from remote manifest
            AssetBundle remoteBundle = AssetBundle.LoadFromFile(Path.Combine(absoluteTempPath, BUNDLE_MANAGER_MASTER_BUNDLE));
            if (remoteBundle == null)
            {
                OVRBundleTool.PrintError("Failed to load remote asset bundle manifest file.");
                return(false);
            }
            AssetBundleManifest remoteManifest = remoteBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

            Dictionary <string, Hash128> remoteBundleToHash = new Dictionary <string, Hash128>();
            if (remoteManifest != null)
            {
                string[] assetBundles = remoteManifest.GetAllAssetBundles();
                foreach (string bundleName in assetBundles)
                {
                    remoteBundleToHash[bundleName] = remoteManifest.GetAssetBundleHash(bundleName);
                }
            }
            remoteBundle.Unload(true);

            // Load hashes from local manifest
            AssetBundle localBundle = AssetBundle.LoadFromFile(BUNDLE_MANAGER_OUTPUT_PATH + "\\" + BUNDLE_MANAGER_MASTER_BUNDLE
                                                               + "\\" + BUNDLE_MANAGER_MASTER_BUNDLE);
            if (localBundle == null)
            {
                OVRBundleTool.PrintError("<color=red>Failed to load local asset bundle manifest file.\n</color>");
                return(false);
            }
            AssetBundleManifest localManifest = localBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

            if (localManifest != null)
            {
                Hash128 zeroHash = new Hash128(0, 0, 0, 0);

                // Build a list of dirty bundles that will have to be transfered
                string relativeSceneBundlesPath = Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, BUNDLE_MANAGER_MASTER_BUNDLE);
                bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, BUNDLE_MANAGER_MASTER_BUNDLE));
                string[] assetBundles = localManifest.GetAllAssetBundles();
                foreach (string bundleName in assetBundles)
                {
                    if (!remoteBundleToHash.ContainsKey(bundleName))
                    {
                        bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, bundleName));
                    }
                    else
                    {
                        if (remoteBundleToHash[bundleName] != localManifest.GetAssetBundleHash(bundleName))
                        {
                            bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, bundleName));
                        }
                        remoteBundleToHash[bundleName] = zeroHash;
                    }
                }

                OVRBundleTool.PrintLog(bundlesToTransfer.Count + " dirty bundle(s) will be transfered.\n");
            }
        }
        else
        {
            if (output.Contains("does not exist"))
            {
                // Fresh install of asset bundles, transfer all asset bundles
                OVRBundleTool.PrintLog("Manifest file not found. Transfering all bundles . . . ");

                string[] mkdirCommand = { "-d shell", "mkdir -p", "\"" + externalSceneCache + "\"" };
                if (adbTool.RunCommand(mkdirCommand, null, out output, out error) == 0)
                {
                    string absoluteSceneBundlePath = Path.Combine(Path.Combine(Application.dataPath, ".."),
                                                                  Path.Combine(BUNDLE_MANAGER_OUTPUT_PATH, BUNDLE_MANAGER_MASTER_BUNDLE));

                    string[] assetBundlePaths = Directory.GetFiles(absoluteSceneBundlePath);
                    if (assetBundlePaths.Length != 0)
                    {
                        foreach (string path in assetBundlePaths)
                        {
                            if (!path.Contains(".manifest"))
                            {
                                bundlesToTransfer.Add(path);
                            }
                        }
                    }
                    else
                    {
                        OVRBundleTool.PrintError("Failed to locate scene bundles to transfer.");
                        return(false);
                    }
                }
            }
        }

        // If any adb error occured during manifest calculation, print it and return false
        if (!string.IsNullOrEmpty(error) || output.Contains("error"))
        {
            OVRBundleTool.PrintError(string.IsNullOrEmpty(error) ? output : error);
            return(false);
        }

        // Transfer bundles to device
        DateTime transferStart = DateTime.Now;

        foreach (string bundle in bundlesToTransfer)
        {
            string   absoluteBundlePath = Path.Combine(Path.Combine(Application.dataPath, ".."), bundle);
            string[] pushBundleCommand  = { "-d push", "\"" + absoluteBundlePath + "\"", "\"" + externalSceneCache + "\"" };
            adbTool.RunCommandAsync(pushBundleCommand, null);
        }
        Debug.Log("[OVRBundleManager] - Transfer took " + (DateTime.Now - transferStart).TotalSeconds + " seconds.");

        // Delete stale bundles on device
        if (bundlesToDelete.Count > 0)
        {
            foreach (string bundle in bundlesToDelete)
            {
                string   bundlePath          = externalSceneCache + "/" + bundle;
                string[] deleteBundleCommand = { "-d shell", "rm", "\"" + bundlePath + "\"" };
                adbTool.RunCommandAsync(deleteBundleCommand, null);
            }
            OVRBundleTool.PrintLog("Deleted " + bundlesToDelete.Count + " bundle(s) that were stale");
        }

        return(true);
    }
Пример #33
0
 internal static GameObject GetPrefab()
 {
     return(assetBundle?.LoadAsset <GameObject>("assets/Bridge.prefab"));
 }
Пример #34
0
 internal static Texture LoadCharacterIcon(string characterName)
 {
     return(mainAssetBundle.LoadAsset <Texture>("tex" + characterName + "Icon"));
 }
Пример #35
0
        public override void OnLoad() // Called once, when mod is loading after game is fully loaded
        {
            // Create BottleRecyclingManager / Desk Trigger
            GameObject bottleRecyclingTrigger = GameObject.CreatePrimitive(PrimitiveType.Cube);

            bottleRecyclingTrigger.name = "Bottle Recycling Manager";
            bottleRecyclingTrigger.transform.position                  = new Vector3(-1551.096f, 4.712f, 1182.784f);
            bottleRecyclingTrigger.transform.localEulerAngles          = new Vector3(-90, 0, 61.256f);
            bottleRecyclingTrigger.transform.localScale                = new Vector3(0.4274191f, 0.5956179f, 0.1249701f);
            bottleRecyclingTrigger.GetComponent <Collider>().isTrigger = true;
            bottleRecyclingManager = bottleRecyclingTrigger.AddComponent <BottleRecyclingManager>();
            GameObject.Destroy(bottleRecyclingTrigger.GetComponent <MeshRenderer>());
            GameObject.Destroy(bottleRecyclingTrigger.GetComponent <MeshFilter>());

            // Create Receive Money Trigger
            GameObject receiveMoneyTrigger = GameObject.CreatePrimitive(PrimitiveType.Cube);

            receiveMoneyTrigger.name  = "Bottle Receive Money Trigger";
            receiveMoneyTrigger.layer = LayerMask.NameToLayer("DontCollide");
            receiveMoneyTrigger.transform.position                  = new Vector3(-1551.336f, 5.0255f, 1183.061f);
            receiveMoneyTrigger.transform.localEulerAngles          = new Vector3(-90, 0, 57.398f);
            receiveMoneyTrigger.transform.localScale                = new Vector3(0.2007769f, 0.5619151f, 0.8257601f);
            receiveMoneyTrigger.GetComponent <Collider>().isTrigger = true;
            GameObject.Destroy(receiveMoneyTrigger.GetComponent <MeshRenderer>());
            GameObject.Destroy(receiveMoneyTrigger.GetComponent <MeshFilter>());
            bottleRecyclingManager.receiveMoneyTrigger = receiveMoneyTrigger.transform;

            // Create Recycling Prices Note
            if ((bool)useAdditionalStoreGfx.GetValue())
            {
                GameObject bottleDepositsNoteVisual = GameObject.CreatePrimitive(PrimitiveType.Plane);
                GameObject.Destroy(bottleDepositsNoteVisual.GetComponent <Collider>());
                bottleDepositsNoteVisual.transform.position         = new Vector3(-1551.484f, 4.36f, 1182.2f);
                bottleDepositsNoteVisual.transform.localEulerAngles = new Vector3(270, 327.354f, 0);
                bottleDepositsNoteVisual.transform.localScale       = new Vector3(0.023f, 0.02f, 0.032f);
                bottleDepositsNoteVisual.name           = "Bottle Deposits Note Visual";
                bottleRecyclingManager.pricesNoteVisual = bottleDepositsNoteVisual.transform;

                GameObject bottleDepositsNote = GameObject.CreatePrimitive(PrimitiveType.Cube);
                bottleDepositsNote.name  = "Bottle Deposits Note";
                bottleDepositsNote.layer = LayerMask.NameToLayer("DontCollide");
                bottleDepositsNote.transform.position                    = new Vector3(-1551.484f, 4.36f, 1182.2f);
                bottleDepositsNote.transform.localEulerAngles            = new Vector3(0, -32.646f, 0);
                bottleDepositsNote.transform.localScale                  = new Vector3(0.1900704f, 0.2755774f, 0.001717138f);
                bottleDepositsNote.GetComponent <Collider>().isTrigger   = true;
                bottleDepositsNote.GetComponent <MeshRenderer>().enabled = false;
                bottleRecyclingManager.pricesNote = bottleDepositsNote.transform;
            }

            // Create BeercaseManager
            if ((bool)useFilledBeercases.GetValue())
            {
                GameObject _beerCaseManager = GameObject.CreatePrimitive(PrimitiveType.Cube);
                beerCaseManager      = _beerCaseManager.AddComponent <BeercaseManager>();
                beerCaseManager.name = "Beercase Manager";
                beerCaseManager.GetComponent <Collider>().isTrigger = true;
                beerCaseManager.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
                GameObject.Destroy(beerCaseManager.GetComponent <MeshRenderer>());
                GameObject.Destroy(beerCaseManager.GetComponent <MeshFilter>());
            }

            // Custom Bottles
            if ((bool)useCustomBottles.GetValue())
            {
                string[] customBottles = null;
                try
                {
                    customBottles = System.IO.File.ReadAllLines(System.IO.Path.Combine(ModLoader.GetModConfigFolder(this), "custom_bottles.txt"));
                }
                catch { }

                if (customBottles != null)
                {
                    foreach (string s in customBottles)
                    {
                        if (s.StartsWith("//") || string.IsNullOrEmpty(s)) // ignore comments
                        {
                            continue;
                        }

                        string[] chars = s.Split('=');
                        if (chars.Length > 1)
                        {
                            if (int.TryParse(chars[1], out int _price))
                            {
                                bottleRecyclingManager.customBottles.Add(chars[0]);
                                bottleRecyclingManager.customBottlePrices.Add(_price);
                            }
                        }
                    }
                }
            }

            ab = LoadAssets.LoadBundle(this, "bottlerecyclingbundle"); // load assetbundle
            LoadSaveFile();                                            // load savefile

            // apply bottle deposits note material
            if (bottleRecyclingManager.pricesNote != null)
            {
                Material noteMaterial = ab.LoadAsset("bottleDepositNoteMat") as Material;
                try
                {
                    bottleRecyclingManager.pricesNoteVisual.GetComponent <MeshRenderer>().material = GameObject.Instantiate(noteMaterial) as Material;
                }
                catch { }
            }

            ab.Unload(false); // unload assetbundle
        }
Пример #36
0
        private static void CreateAndPatchPacks()
        {
            var nBattery = new CbBattery // Calling the CustomBatteries API to patch this item as a Battery
            {
                EnergyCapacity    = 2500,
                ID                = "NuclearBattery",
                Name              = "Ion-fused Nuclear Battery",
                FlavorText        = "A Battery made by the Precursor Technology and its interaction with Nuclear Power.",
                CraftingMaterials = { TechType.UraniniteCrystal, TechType.UraniniteCrystal, TechType.PrecursorIonCrystal, TechType.Lead, TechType.Lead, TechType.Nickel },
                UnlocksWith       = TechType.UraniniteCrystal,
                CustomIcon        = new Atlas.Sprite(assetBundle.LoadAsset <Sprite>("NuclearBattery")),
                CBModelData       = new CBModelData
                {
                    CustomTexture       = assetBundle.LoadAsset <Texture2D>("NuclearBatteryskin"),
                    CustomIllumMap      = assetBundle.LoadAsset <Texture2D>("NuclearBatteryillum"),
                    CustomSpecMap       = assetBundle.LoadAsset <Texture2D>("NuclearBatteryspec"),
                    CustomIllumStrength = 0.95f,
                    UseIonModelsAsBase  = true
                },
            };

            nBattery.Patch();

            var nPowercell = new CbPowerCell // Calling the CustomBatteries API to patch this item as a Power Cell
            {
                EnergyCapacity    = nBattery.EnergyCapacity * 2,
                ID                = "NuclearPowercell",
                Name              = "Ion-fused Nuclear Power Cell",
                FlavorText        = "A Power Cell made by the Precursor Technology and its interaction with Nuclear Power.",
                CraftingMaterials = { nBattery.TechType, nBattery.TechType, TechType.Silicone },
                UnlocksWith       = nBattery.TechType,
                CustomIcon        = new Atlas.Sprite(assetBundle.LoadAsset <Sprite>("NuclearCell")),
                CBModelData       = new CBModelData
                {
                    CustomTexture       = assetBundle.LoadAsset <Texture2D>("NuclearCellskin"),
                    CustomIllumMap      = assetBundle.LoadAsset <Texture2D>("NuclearCellillum"),
                    CustomSpecMap       = assetBundle.LoadAsset <Texture2D>("NuclearCellspec"),
                    UseIonModelsAsBase  = true,
                    CustomIllumStrength = 1.2f
                },
            };

            nPowercell.Patch();

            var unBattery = new CbBattery // Calling the CustomBatteries API to patch this item as a Battery
            {
                EnergyCapacity    = 5250,
                ID                = "VolatileBattery",
                Name              = "Volatile Radioactive Battery",
                FlavorText        = "This Battery pulsates with Radioactive energy. Extreme caution when handling; Contains too much Uranium!",
                CraftingMaterials = { nBattery.TechType, TechType.UraniniteCrystal, TechType.UraniniteCrystal, TechType.UraniniteCrystal, TechType.Lead, TechType.Lead, TechType.Sulphur, TechType.Sulphur, TechType.Sulphur },
                UnlocksWith       = nBattery.TechType,
                CustomIcon        = new Atlas.Sprite(assetBundle.LoadAsset <Sprite>("VolatileBattery")),
                CBModelData       = new CBModelData
                {
                    CustomTexture       = assetBundle.LoadAsset <Texture2D>("VolatileBatteryskin"),
                    CustomIllumMap      = assetBundle.LoadAsset <Texture2D>("VolatileBatteryillum"),
                    CustomSpecMap       = assetBundle.LoadAsset <Texture2D>("VolatileBatteryspec"),
                    UseIonModelsAsBase  = true,
                    CustomIllumStrength = 1.2f
                },
            };

            unBattery.Patch();

            var unPowercell = new CbPowerCell // Calling the CustomBatteries API to patch this item as a Power Cell
            {
                EnergyCapacity    = unBattery.EnergyCapacity * 2,
                ID                = "VolatilePowercell",
                Name              = "Volatile Radioactive Power Cell",
                FlavorText        = "This Power Cell pulsates with Radioactive energy. Extreme caution when handling; Contains too much Uranium!",
                CraftingMaterials = { unBattery.TechType, unBattery.TechType, TechType.Silicone },
                UnlocksWith       = unBattery.TechType,
                CustomIcon        = new Atlas.Sprite(assetBundle.LoadAsset <Sprite>("VolatileCell")),
                CBModelData       = new CBModelData
                {
                    CustomTexture       = assetBundle.LoadAsset <Texture2D>("VolatileCellskin"),
                    CustomIllumMap      = assetBundle.LoadAsset <Texture2D>("VolatileCellillum"),
                    CustomSpecMap       = assetBundle.LoadAsset <Texture2D>("VolatileCellspec"),
                    UseIonModelsAsBase  = true,
                    CustomIllumStrength = 1.2f
                },
            };

            unPowercell.Patch();
        }
Пример #37
0
 public static void Test4()
 {
     AssetBundle ab      = AssetBundle.LoadFromFile(Application.dataPath + "/../AssetBundle/" + EditorUserBuildSettings.activeBuildTarget.ToString() + "/cube (1)");
     GameObject  gameobj = UnityEngine.Object.Instantiate(ab.LoadAsset <GameObject>("Cube (1)"));
 }
Пример #38
0
 public T LoadAsset <T>(string assetName) where T : Object
 {
     return(_assetBundle.LoadAsset <T>(assetName));
 }
    // Use this for initialization
    IEnumerator Start()
    {
        string path = @"file:///F:\Test\AssetBundleProject\AssetBundles\cubewall.unity3d";
        //AssetBundle ab = AssetBundle.LoadFromFile("AssetBundles/cubewall.unity3d");
        //GameObject cubePrefab = ab.LoadAsset<GameObject>("CubeWall");
        //Instantiate(cubePrefab);
        //Object[] objs = ab.LoadAllAssets();
        //foreach(Object o in objs)
        //{
        //    Instantiate(o);
        //}

        //第一种加载AB的方式 LoadFromMemoryAsync
        //AssetBundleCreateRequest request =  AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
        //yield return request;
        //AssetBundle ab = request.assetBundle;

        //AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));

        // 第二种加载AB的方式 LoadFromFile
        //AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
        //yield return request;
        //AssetBundle ab = request.assetBundle;

        // 第三种加载AB的方式 www
        //while (Caching.ready == false)
        //{
        //    yield return null;
        //}

        ////WWW www = WWW.LoadFromCacheOrDownload(path, 1);
        //WWW www = WWW.LoadFromCacheOrDownload(@"http://localhost/AssetBundles/cubewall.unity3d", 1);

        //yield return www;
        //if (string.IsNullOrEmpty(www.error)== false)
        //{
        //    Debug.Log(www.error);
        //    yield break;
        //}
        //AssetBundle ab = www.assetBundle;

        //第四种方式 使用UnityWebRequest

        //string url = @"file:///F:\Test\AssetBundleProject\AssetBundles\cubewall.unity3d";
        string url = @"http://localhost/AssetBundles/cubewall.unity3d";

        UnityWebRequest request = UnityWebRequest.GetAssetBundle(url);

        yield return(request.Send());

        //AssetBundle ab = DownloadHandlerAssetBundle.GetContent (request);
        AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;

        // 使用里面的资源
        GameObject cubePrefab = ab.LoadAsset <GameObject>("CubeWall");

        Instantiate(cubePrefab);

        AssetBundle         maifestAB = AssetBundle.LoadFromFile("AssetBundles/assetBundles");
        AssetBundleManifest manifest  = maifestAB.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

        //foreach(string name in manifest.GetAllAssetBundles())
        //{
        //    print(name);
        //}
        string[] strs = manifest.GetAllDependencies("cubewall.unity3d");
        foreach (string item in strs)
        {
            print(item);
            AssetBundle.LoadFromFile("AssetBundles/" + item);
        }
    }
    private static bool PullSceneBundles(string absoluteTempPath, string externalSceneCache)
    {
        List <string> bundlesToTransfer = new List <string>();
        string        manifestFilePath  = externalSceneCache + "/" + SQP_SCENE_BUNDLE;

        string[] pullManifestCommand = { "-d pull", "\"" + manifestFilePath + "\"", "\"" + absoluteTempPath + "\"" };

        string output, error;

        if (PXR_ADBTool.GetInstance().RunCommand(pullManifestCommand, null, out output, out error) == 0)
        {
            // Load hashes from remote manifest
            AssetBundle remoteBundle = AssetBundle.LoadFromFile(Path.Combine(absoluteTempPath, SQP_SCENE_BUNDLE));
            if (remoteBundle == null)
            {
                PXR_SceneQucikPreviewEW.PrintError("Failed to load remote asset bundle manifest file.");
                return(false);
            }
            AssetBundleManifest remoteManifest = remoteBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

            Dictionary <string, Hash128> remoteBundleToHash = new Dictionary <string, Hash128>();
            if (remoteManifest != null)
            {
                string[] assetBundles = remoteManifest.GetAllAssetBundles();
                foreach (string bundleName in assetBundles)
                {
                    remoteBundleToHash[bundleName] = remoteManifest.GetAssetBundleHash(bundleName);
                }
            }
            remoteBundle.Unload(true);

            AssetBundle localBundle = AssetBundle.LoadFromFile(SQP_BUNDLE_PATH + "\\" + SQP_SCENE_BUNDLE
                                                               + "\\" + SQP_SCENE_BUNDLE);
            if (localBundle == null)
            {
                PXR_SceneQucikPreviewEW.PrintError("Failed to load local asset bundle manifest file.");
                return(false);
            }
            AssetBundleManifest localManifest = localBundle.LoadAsset <AssetBundleManifest>("AssetBundleManifest");

            if (localManifest != null)
            {
                Hash128 zeroHash = new Hash128(0, 0, 0, 0);

                // Build a list of dirty bundles that will have to be transfered
                string relativeSceneBundlesPath = Path.Combine(SQP_BUNDLE_PATH, SQP_SCENE_BUNDLE);
                bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, SQP_SCENE_BUNDLE));
                string[] assetBundles = localManifest.GetAllAssetBundles();
                foreach (string bundleName in assetBundles)
                {
                    if (!remoteBundleToHash.ContainsKey(bundleName))
                    {
                        bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, bundleName));
                    }
                    else
                    {
                        if (remoteBundleToHash[bundleName] != localManifest.GetAssetBundleHash(bundleName))
                        {
                            bundlesToTransfer.Add(Path.Combine(relativeSceneBundlesPath, bundleName));
                        }
                        remoteBundleToHash[bundleName] = zeroHash;
                    }
                }

                PXR_SceneQucikPreviewEW.PrintLog(bundlesToTransfer.Count + " dirty bundle(s) will be transfered.\n");
            }
        }
        else
        {
            if (output.Contains("does not exist") || output.Contains("No such file or directory"))
            {
                PXR_SceneQucikPreviewEW.PrintLog("Manifest file not found. Transfering all bundles . . . ");

                string[] mkdirCommand = { "-d shell", "mkdir -p", "\"" + externalSceneCache + "\"" };
                if (PXR_ADBTool.GetInstance().RunCommand(mkdirCommand, null, out output, out error) == 0)
                {
                    string absoluteSceneBundlePath = Path.Combine(Path.Combine(Application.dataPath, ".."),
                                                                  Path.Combine(SQP_BUNDLE_PATH, SQP_SCENE_BUNDLE));

                    string[] assetBundlePaths = Directory.GetFiles(absoluteSceneBundlePath);
                    if (assetBundlePaths.Length == 0)
                    {
                        PXR_SceneQucikPreviewEW.PrintError("Failed to locate scene bundles to transfer.");
                        return(false);
                    }
                    foreach (string path in assetBundlePaths)
                    {
                        if (!path.Contains(".manifest"))
                        {
                            bundlesToTransfer.Add(path);
                        }
                    }
                }
            }
        }

        if (!string.IsNullOrEmpty(error) || output.Contains("error"))
        {
            PXR_SceneQucikPreviewEW.PrintError(string.IsNullOrEmpty(error) ? output : error);
            return(false);
        }

        foreach (string bundle in bundlesToTransfer)
        {
            string   absoluteBundlePath = Path.Combine(Path.Combine(Application.dataPath, ".."), bundle);
            string[] pushBundleCommand  = { "-d push", "\"" + absoluteBundlePath + "\"", "\"" + externalSceneCache + "\"" };
            PXR_ADBTool.GetInstance().RunCommandAsync(pushBundleCommand, null);
        }

        return(true);
    }
Пример #41
0
    // 从资源包初始化脚本环境
    public void InitializeFromAssetBundle(AssetBundle scriptsAssetBundle)
    {
        m_clsAssetBundle = scriptsAssetBundle;

        #if UNITY_EDITOR
        float timeStart = Time.realtimeSinceStartup;
        uint monoStart = Profiler.GetMonoUsedSize();
        #endif

        // 获取默认的脚本实例
        m_clsEnv = ToCSLight.CreateEnvironment();
        m_clsContent = m_clsEnv.CreateContent();

        // 预注册脚本类
        #if UNITY_EDITOR && !EDITOR_FORCE_ASSET_BUNDLE
        string rootPath = Application.dataPath + "/CSLight/Editor/CSLogic";
        string[] files = System.IO.Directory.GetFiles(rootPath, "*.cs", System.IO.SearchOption.AllDirectories);
        foreach (var file in files)
        {
            string className = System.IO.Path.GetFileNameWithoutExtension(file);
            m_clsEnv.RegType(new CLS_Type_Class(className, file.Replace('\\', '/')));
        }
        #else
        StringHolder classHolder = m_clsAssetBundle.LoadAsset("class", typeof(StringHolder)) as StringHolder;
        foreach (string className in classHolder.content)
        {
            m_clsEnv.RegType(new CLS_Type_Class(className, className));
        }
        #endif

        #if UNITY_EDITOR
        Debug.Log("script init cost time: " + (Time.realtimeSinceStartup - timeStart));
        Debug.Log(string.Format("script init cost memory: {0:0.00}MB", (Profiler.GetMonoUsedSize() - monoStart) / (1024f * 1024f)));
        timeStart = Time.realtimeSinceStartup;
        #endif
    }
Пример #42
0
        //异步加载资源
        private IEnumerator LoadAssetAsync <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab = false, Transform parent = null, bool isUI = false) where T : UnityEngine.Object
        {
            DateTime beginTime = DateTime.Now;

            if (_isLoading)
            {
                yield return(_loadWait);
            }

            _isLoading = true;

            yield return(Main.Current.StartCoroutine(LoadDependenciesAssetBundleAsync(info.AssetBundleName)));

            DateTime waitTime = DateTime.Now;

            UnityEngine.Object asset = null;

            if (Mode == ResourceLoadMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    loadingAction?.Invoke(request.progress);
                    yield return(null);
                }
                asset = request.asset;
                if (asset)
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
                else
                {
                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!");
                }
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!");
                    }
                }
                else
                {
                    if (_assetBundles.ContainsKey(info.AssetBundleName))
                    {
                        loadingAction?.Invoke(1);
                        yield return(null);

                        asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                        if (asset)
                        {
                            if (isPrefab)
                            {
                                asset = ClonePrefab(asset as GameObject, parent, isUI);
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                        }
                    }
                    else
                    {
                        using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                        {
                            request.SendWebRequest();
                            while (!request.isDone)
                            {
                                loadingAction?.Invoke(request.downloadProgress);
                                yield return(null);
                            }
                            if (!request.isNetworkError && !request.isHttpError)
                            {
                                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                                if (bundle)
                                {
                                    asset = bundle.LoadAsset <T>(info.AssetPath);
                                    if (asset)
                                    {
                                        if (isPrefab)
                                        {
                                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                                        }
                                    }
                                    else
                                    {
                                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                    }

                                    if (IsCacheAssetBundle)
                                    {
                                        if (!_assetBundles.ContainsKey(info.AssetBundleName))
                                        {
                                            _assetBundles.Add(info.AssetBundleName, bundle);
                                        }
                                    }
                                    else
                                    {
                                        bundle.Unload(false);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                            }
                        }
                    }
                }
#else
                if (_assetBundles.ContainsKey(info.AssetBundleName))
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                    }
                }
                else
                {
                    using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                    {
                        request.SendWebRequest();
                        while (!request.isDone)
                        {
                            loadingAction?.Invoke(request.downloadProgress);
                            yield return(null);
                        }
                        if (!request.isNetworkError && !request.isHttpError)
                        {
                            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                            if (bundle)
                            {
                                asset = bundle.LoadAsset <T>(info.AssetPath);
                                if (asset)
                                {
                                    if (isPrefab)
                                    {
                                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                }

                                if (IsCacheAssetBundle)
                                {
                                    if (!_assetBundles.ContainsKey(info.AssetBundleName))
                                    {
                                        _assetBundles.Add(info.AssetBundleName, bundle);
                                    }
                                }
                                else
                                {
                                    bundle.Unload(false);
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                        }
                    }
                }
#endif
            }

            DateTime endTime = DateTime.Now;

            GlobalTools.LogInfo(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒  加载耗时:{4}秒", asset ? "成功" : "失败", Mode
                                              , Mode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(_assetBundleRootPath)
                                              , (waitTime - beginTime).TotalSeconds, (endTime - waitTime).TotalSeconds));

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    asset.Cast <DataSetBase>().Fill(dataSet.Data);
                }

                loadDoneAction?.Invoke(asset as T);
            }
            asset = null;

            _isLoading = false;
        }
Пример #43
0
    public void SetObjectModel(OSLibObject obj, AssetBundle assets)
    {
        _objectModel = obj;
        _nbConfMats = _objectModel.GetModules().GetStandardModuleList().Count;
        // apply default materials
        foreach (OSLibModule mod in obj.GetModules ().GetStandardModuleList())
        {
            Transform modTarget = transform.Find (mod.GetModuleType ());
            Color colorText = new Color(0.78f,0.78f,0.78f,1.0f);
            if (modTarget != null)
            {
                if (mod.GetColorList ().Count > 0)
                {
                    OSLibColor color = OSLibBuilderUtils.
                        GetFirstColorOfType(mod, mod.GetModuleType ());
                    modTarget.GetComponent<Renderer>().material.color = color.GetColor ();
                    if(modTarget.GetComponent<MeshRenderer>())
                    {
                        modTarget.GetComponent<Renderer>().material.mainTexture = null;
                        if((modTarget.GetComponent<Renderer>().material.HasProperty("_DecalTex")) && (usefullData.lowTechnologie))
                        {
                            modTarget.GetComponent<Renderer>().material.mainTexture = modTarget.GetComponent<Renderer>().material.GetTexture("_DecalTex");
                        }
                    }

                    if(color.GetColorType2()!=null)
                    {
                        Transform modTarget2 = transform.Find (color.GetColorType2());
                        if (modTarget2 != null)
                        {
                            Color color2 = color.GetColor2();
                            modTarget2.GetComponent<Renderer>().material.mainTexture = null;
                            modTarget2.GetComponent<Renderer>().material.color = color2;
                        }
                    }
                }
                else if (mod.GetTextureList ().Count > 0)
                {
                    OSLibTexture textData = OSLibBuilderUtils.
                                                GetFirstTextureOfType (mod, mod.GetModuleType ());

                    Texture2D text = assets.LoadAsset (textData.GetFilePath (),
                                                       typeof (Texture2D)) as Texture2D;
                    if(modTarget.GetComponent<Renderer>().material.shader.name.Contains("Pointcube"))
                    {
                        Debug.Log(text.name + " TEXTURES");
                        modTarget.GetComponent<Renderer>().material.SetTexture("_Diffuse",text);
                        /*modTarget.GetComponent<Renderer>().material.SetTexture("_Normal",text);
                        modTarget.GetComponent<Renderer>().material.SetTexture("_HueMask",text);
                        modTarget.GetComponent<Renderer>().material.SetTexture("_SpecMask",text);*/
                        modTarget.GetComponent<Renderer>().material.color = colorText;
                        float scale = textData.GetScale();

                        if(textData.GetTextureType2()!=null)
                        {
                            Transform modTarget2 = transform.Find (textData.GetTextureType2());
                            if (modTarget2 != null)
                            {
                                Texture2D text2 = assets.LoadAsset (textData.GetFilePath2 (),
                                                                    typeof (Texture2D)) as Texture2D;
                                modTarget2.GetComponent<Renderer>().material.mainTexture = text2;
                                modTarget2.GetComponent<Renderer>().material.color = colorText;
                                modTarget2.GetComponent<Renderer>().material.SetTextureScale("_MainTex",new Vector2(scale,scale));
                            }
                        }
                    }
                    else{
                        modTarget.GetComponent<Renderer>().material.mainTexture = text;
                        modTarget.GetComponent<Renderer>().material.color = colorText;
                        float scale = textData.GetScale();
                        if (modTarget.name.CompareTo("plage")==0)
                            scale/=2.0f;
                        modTarget.GetComponent<Renderer>().material.SetTextureScale("_MainTex",new Vector2(scale,scale));

                        if(textData.GetTextureType2()!=null)
                        {
                            Transform modTarget2 = transform.Find (textData.GetTextureType2());
                            if (modTarget2 != null)
                            {
                                Texture2D text2 = assets.LoadAsset (textData.GetFilePath2 (),
                                                           typeof (Texture2D)) as Texture2D;
                                modTarget2.GetComponent<Renderer>().material.mainTexture = text2;
                                modTarget2.GetComponent<Renderer>().material.color = colorText;
                                modTarget2.GetComponent<Renderer>().material.SetTextureScale("_MainTex",new Vector2(scale,scale));
                            }
                        }
                    }
                }
                subObjects.Add(mod.GetModuleType(),0);
            }
        }
    }
Пример #44
0
        /// <summary>
        /// Add a UI package from two assetbundles with a optional main asset name.
        /// </summary>
        /// <param name="desc">A assetbunble contains description file.</param>
        /// <param name="res">A assetbundle contains resources.</param>
        /// <param name="mainAssetName">Main asset name. e.g. Basics_fui.bytes</param>
        /// <returns>UIPackage</returns>
        public static UIPackage AddPackage(AssetBundle desc, AssetBundle res, string mainAssetName)
        {
            byte[] source = null;
#if (UNITY_5 || UNITY_5_3_OR_NEWER)
            if (mainAssetName != null)
            {
                TextAsset ta = desc.LoadAsset <TextAsset>(mainAssetName);
                if (ta != null)
                {
                    source = ta.bytes;
                }
            }
            else
            {
                string[] names         = desc.GetAllAssetNames();
                string   searchPattern = "_fui";
                foreach (string n in names)
                {
                    if (n.IndexOf(searchPattern) != -1)
                    {
                        TextAsset ta = desc.LoadAsset <TextAsset>(n);
                        if (ta != null)
                        {
                            source        = ta.bytes;
                            mainAssetName = Path.GetFileNameWithoutExtension(n);
                            break;
                        }
                    }
                }
            }
#else
            if (mainAssetName != null)
            {
                TextAsset ta = (TextAsset)desc.Load(mainAssetName, typeof(TextAsset));
                if (ta != null)
                {
                    source = ta.bytes;
                }
            }
            else
            {
                source        = ((TextAsset)desc.mainAsset).bytes;
                mainAssetName = desc.mainAsset.name;
            }
#endif
            if (source == null)
            {
                throw new Exception("FairyGUI: no package found in this bundle.");
            }

            if (desc != res)
            {
                desc.Unload(true);
            }

            ByteBuffer buffer = new ByteBuffer(source);

            UIPackage pkg = new UIPackage();
            pkg._resBundle  = res;
            pkg._fromBundle = true;
            int    pos = mainAssetName.IndexOf("_fui");
            string assetNamePrefix;
            if (pos != -1)
            {
                assetNamePrefix = mainAssetName.Substring(0, pos);
            }
            else
            {
                assetNamePrefix = mainAssetName;
            }
            if (!pkg.LoadPackage(buffer, res.name, assetNamePrefix))
            {
                return(null);
            }

            _packageInstById[pkg.id]     = pkg;
            _packageInstByName[pkg.name] = pkg;
            _packageList.Add(pkg);

            return(pkg);
        }