/// <summary> /// Call script of script path (relative) specify /// /// We don't recommend use this method, please use ImportScript which has Caching! /// </summary> /// <param name="scriptRelativePath"></param> /// <returns></returns> public object CallScript(string scriptRelativePath) { if (string.IsNullOrEmpty(scriptRelativePath)) { return(null); } Debuger.Assert(HasScript(scriptRelativePath), "Not exist Lua: " + scriptRelativePath); var scriptPath = GetScriptPath(scriptRelativePath); byte[] script; if (Log.IsUnityEditor) { script = File.ReadAllBytes(scriptPath); } else { //TODO 热更新从PersistentDataPath路径读取 //script = KResourceModule.LoadSyncFromPersistentDataPath(scriptPath); script = KResourceModule.LoadSyncFromStreamingAssets(scriptPath); } var ret = ExecuteScript(script, scriptRelativePath); return(ret); }
public int NewColumn(string colName, string defineStr = "") { Debuger.Assert(!string.IsNullOrEmpty(colName)); var newHeader = new HeaderInfo { ColumnIndex = ColIndex.Count + 1, HeaderName = colName, HeaderDef = defineStr, }; ColIndex.Add(colName, newHeader); ColCount++; //string[] rowStrs; //if (TabInfo.TryGetValue(0, out rowStrs)) //{ // // 已经存在,进行修改 // var oldCol = rowStrs; // var newColRow = TabInfo[0] = new string[ColCount]; // 0 行是行头 // oldCol.CopyTo(newColRow, 0); // newColRow[newColRow.Length - 1] = newHeader.ToColumnString(); //} //else //{ // TabInfo[0] = new string[ColCount]; // 0 行是行头 // TabInfo[0][ColCount - 1] = newHeader.ToColumnString(); //} return(ColCount); }
/// <summary> /// Try to load script and init. /// Script will be cached, /// But in development, script cache can be clear, which will be load and init in the next time /// /// 开发阶段经常要使用Lua热重载,热重载过后,要确保OnInit重新执行 /// </summary> bool CheckInitScript(bool showWarn = false) { if (!IsCachedLuaTable) { ClearLuaTableCache(); } var relPath = UILuaPath; var luaModule = KSGame.Instance.LuaModule; object scriptResult; if (!luaModule.TryImport(relPath, out scriptResult)) { if (showWarn) { Log.LogWarning("Import UI Lua Script failed: {0}", relPath); } return(false); } scriptResult = KSGame.Instance.LuaModule.CallScript(relPath); Debuger.Assert(scriptResult is LuaTable, "{0} Script Must Return Lua Table with functions!", UITemplateName); _luaTable = scriptResult as LuaTable; var newFuncObj = _luaTable["New"]; // if a New function exist, new a table! if (newFuncObj != null) { var newTableObj = (newFuncObj as LuaFunction).Call(this); _luaTable = newTableObj[0] as LuaTable; } var outlet = this.GetComponent <UILuaOutlet>(); if (outlet != null) { for (var i = 0; i < outlet.OutletInfos.Count; i++) { var outletInfo = outlet.OutletInfos[i]; var gameObj = outletInfo.Object as GameObject; if (gameObj == null || outletInfo.ComponentType == typeof(UnityEngine.GameObject).FullName) { _luaTable[outletInfo.Name] = outletInfo.Object; continue; } if (outletInfo.ComponentType == typeof(UnityEngine.Transform).FullName) { _luaTable[outletInfo.Name] = gameObj.transform; } else if (outletInfo.ComponentType == typeof(UnityEngine.RectTransform).FullName) { _luaTable[outletInfo.Name] = gameObj.GetComponent(typeof(UnityEngine.RectTransform)); } else if (outletInfo.ComponentType == typeof(UnityEngine.Canvas).FullName) { _luaTable.[outletInfo.Name] = gameObj.GetComponent(typeof(UnityEngine.Canvas));
protected void ProcessUISprite(string resourcePath) { var loader = KUIAtlasDep.LoadUIAtlas(resourcePath, (atlas) => { if (!IsDestroy) { //UIAtlas atlas = _obj as UIAtlas; Debuger.Assert(atlas); Debuger.Assert(DependencyComponent); var sprite = DependencyComponent as UISprite; Debuger.Assert(sprite); sprite.atlas = atlas; //对UISpriteAnimation处理 foreach (UISpriteAnimation spriteAnim in this.gameObject.GetComponents <UISpriteAnimation>()) { spriteAnim.RebuildSpriteList(); } } OnFinishLoadDependencies(gameObject); // 返回GameObject而已哦 }); ResourceLoaders.Add(loader); }
private IEnumerator LoadUIAssetBundle(string name, CUILoadState openState) { LoadingUICount++; var request = new UILoadRequest(); yield return(KResourceModule.Instance.StartCoroutine(UiBridge.LoadUIAsset(openState, request))); GameObject uiObj = (GameObject)request.Asset; // 具体加载逻辑结束...这段应该放到Bridge里 uiObj.SetActive(false); uiObj.name = openState.TemplateName; KUIController uiBase = uiObj.AddComponent(openState.UIType) as KUIController; Debuger.Assert(uiBase); openState.UIWindow = uiBase; uiBase.UIName = uiBase.UITemplateName = openState.TemplateName; UiBridge.UIObjectFilter(uiBase, uiObj); openState.IsLoading = false; // Load完 InitWindow(openState, uiBase, openState.OpenWhenFinish, openState.OpenArgs); LoadingUICount--; }
// UILabel... Bitmap Font protected void ProcesBitMapFont(string resPath) { // Load UIFont Prefab var loader = KStaticAssetLoader.Load(resPath, (isOk, o) => { if (!IsDestroy) { var uiFontPrefab = (GameObject)o; Debuger.Assert(uiFontPrefab); uiFontPrefab.transform.parent = DependenciesContainer.transform; var uiFont = uiFontPrefab.GetComponent <UIFont>(); Debuger.Assert(uiFont); var label = DependencyComponent as UILabel; //foreach (UILabel label in gameObject.GetComponents<UILabel>()) { label.bitmapFont = uiFont; } OnFinishLoadDependencies(uiFont); } else { OnFinishLoadDependencies(null); } }); ResourceLoaders.Add(loader); }
private static void AssetBundleManifestLoadCallback(string url, object resultObject) { Debug.Log("AssetBundleManifestLoadCallback: call back " + (resultObject == null ? "object null":" object ready")); if (resultObject != null) { _mainAssetBundle = AssetBundle.LoadFromMemory(resultObject as byte[]); _assetBundleManifest = _mainAssetBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest; if (_assetBundleManifest == null) { _assetBundleManifestLoadFailure = true; } Debuger.Assert(_mainAssetBundle); Debuger.Assert(_assetBundleManifest); //Debug.Log("Total ab: " + _assetBundleManifest.GetAllAssetBundles().Length); foreach (string ab in _assetBundleManifest.GetAllAssetBundles()) { //Debug.Log(ab); } } else { _assetBundleManifestLoadFailure = true; } }
/// <summary> /// Call script of script path (relative) specify /// /// We don't recommend use this method, please use ImportScript which has Caching! /// </summary> /// <param name="path"></param> /// <returns></returns> public object CallScript(string path) { var scriptPath = GetScriptPath(path); byte[] script; HotBytesLoader loader = null; try { loader = HotBytesLoader.Load(scriptPath, LoaderMode.Sync); Debuger.Assert(!loader.IsError, "Something wrong or Not exist Lua: " + scriptPath); script = loader.Bytes; } finally { if (loader != null) { loader.Release(); } } // if (Log.IsUnityEditor) // script = File.ReadAllBytes(scriptPath); // else // script = KResourceModule.LoadSyncFromStreamingAssets(scriptPath); var ret = ExecuteScript(script); return(ret); }
private IEnumerator CoLoadSerializeMaterial() { var matLoadBridge = KAssetFileLoader.Load(Url); while (!matLoadBridge.IsCompleted) { Progress = matLoadBridge.Progress; yield return(null); } var sMat = matLoadBridge.ResultObject as KSerializeMaterial; Debuger.Assert(sMat); Desc = sMat.ShaderName; Debuger.Assert(Mat == null); yield return(KResourceModule.Instance.StartCoroutine(CoGenerateMaterial(Url, sMat))); Debuger.Assert(Mat); matLoadBridge.Release(); //不需要它了 if (Application.isEditor) { KResoourceLoadedAssetDebugger.Create("Material", Url, Mat); } OnFinish(Mat); }
public void Reload() { _cacheTable = null; var ret = LuaModule.Instance.CallScript(LuaPath); Debuger.Assert(ret is LuaTable, "{0} Script Must Return Lua Table with functions!", LuaPath); _cacheTable = ret as LuaTable; }
public T this[int index] { get { Debuger.Assert(index < MaxCount); IntPtr p = (IntPtr)(SourceBytesPtr.ToInt32() + Marshal.SizeOf(typeof(T)) * index); return((T)Marshal.PtrToStructure(p, typeof(T))); } }
/// <summary> /// Different platform's assetBundles is incompatible. /// CosmosEngine put different platform's assetBundles in different folder. /// Here, get Platform name that represent the AssetBundles Folder. /// </summary> /// <returns>Platform folder Name</returns> public static string GetBuildPlatformName() { string buildPlatformName = "Win32"; // default if (Application.isEditor) { var buildTarget = UnityEditor_EditorUserBuildSettings_activeBuildTarget; //UnityEditor.EditorUserBuildSettings.activeBuildTarget; switch (buildTarget) { case "StandaloneWindows": // UnityEditor.BuildTarget.StandaloneWindows: case "StandaloneWindows64": // UnityEditor.BuildTarget.StandaloneWindows64: buildPlatformName = "Win32"; break; case "Android": // UnityEditor.BuildTarget.Android: buildPlatformName = "Android"; break; case "iPhone": // UnityEditor.BuildTarget.iPhone: buildPlatformName = "IOS"; break; default: Debuger.Assert(false); break; } } else { switch (Application.platform) { case RuntimePlatform.Android: buildPlatformName = "Android"; break; case RuntimePlatform.IPhonePlayer: buildPlatformName = "IOS"; break; case RuntimePlatform.WindowsPlayer: case RuntimePlatform.WindowsWebPlayer: buildPlatformName = "Win32"; break; default: Debuger.Assert(false); break; } } if (Quality != KResourceQuality.Sd) // SD no need add { buildPlatformName += Quality.ToString().ToUpper(); } return(buildPlatformName); }
private void Awake() { if (_Instance != null) { Debuger.Assert(_Instance == this); } //InvokeRepeating("CheckGcCollect", 0f, 3f); }
IEnumerator Start() { //KGameSettings.Instance.InitAction += OnGameSettingsInit; var engine = KEngine.AppEngine.New( gameObject, null, new IModuleInitable[] { //KGameSettings.Instance, // UIModule.Instance, }); while (!engine.IsInited) { yield return(null); } var uiName = "DemoHome"; UIModule.Instance.OpenWindow(uiName); Debug.Log("[SettingModule]Table: " + string.Join(",", ExampleSettings.TabFilePaths)); foreach (ExampleSetting exampleInfo in ExampleSettings.GetAll()) { Debug.Log(string.Format("Name: {0}", exampleInfo.Name)); Debug.Log(string.Format("Number: {0}", exampleInfo.Number)); } var info = ExampleSettings.Get("A_1024"); Debuger.Assert(info.Name == "Test1"); var info2 = SubdirExample2Settings.Get(2); Debuger.Assert(info2.Name == "Test2"); var info3 = AppConfigSettings.Get("Test.Cat1"); Debuger.Assert(info3.Value == "Cat1"); ExampleSettings.OnReload = () => { var reloadedInfo = ExampleSettings.Get("C_9888"); Log.Info("Reload ExampleInfos! Now info: {0} -> {1}", "C_9888", reloadedInfo.Name); }; Log.Info("Start reading streamingAssets Test..."); UIModule.Instance.CallUI(uiName, (ui, args) => { var tip = string.Format("Reading from streamingAssets, content: {0}", Encoding.UTF8.GetString(KResourceModule.LoadSyncFromStreamingAssets("TestFile.txt"))); var demoHome = ui as KUIDemoHome; demoHome.TipLabel.text += tip; // Do some UI stuff }); }
public object GetUIComponent(string comName) { if (comName == "Camera") { return(UiCamera); } Debuger.Assert(false); return(null); }
/// <summary> /// Try to load script and init. /// Script will be cached, /// But in development, script cache can be clear, which will be load and init in the next time /// /// 开发阶段经常要使用Lua热重载,热重载过后,要确保OnInit重新执行 /// </summary> bool CheckInitScript(bool showWarn = false) { if (!LuaModule.CacheMode) { ClearLuaTableCache(); } var relPath = UILuaPath; var luaModule = KSGame.Instance.LuaModule; object scriptResult; if (!luaModule.TryImport(relPath, out scriptResult)) { if (showWarn) { Log.LogWarning("Import UI Lua Script failed: {0}", relPath); } return(false); } Debuger.Assert(scriptResult is LuaTable, "{0} Script Must Return Lua Table with functions!", UITemplateName); _luaTable = scriptResult as LuaTable; var newFuncObj = _luaTable.Get <LuaFunction>("new"); // if a New function exist, new a table! if (newFuncObj != null) { #if SLUA var newTableObj = (newFuncObj as LuaFunction).call(this); _luaTable = newTableObj as LuaTable; #else var newTableObj = (newFuncObj as LuaFunction).Call(this); _luaTable = newTableObj[0] as LuaTable; #endif } #if SLUA SetOutlet_Slua(_luaTable); #else SetOutlet(_luaTable); #endif var luaInitObj = _luaTable.Get <LuaFunction>("OnInit"); Debuger.Assert(luaInitObj is LuaFunction, "Must have OnInit function - {0}", UIName); // set table variable `Controller` to this #if SLUA _luaTable["Controller"] = this; (luaInitObj as LuaFunction).call(_luaTable, this); #else _luaTable.SetInPath("Controller", this); (luaInitObj as LuaFunction).Call(_luaTable, this); #endif return(true); }
/// <summary> /// 目前用在非热更部分,lua中请使用OpenWindow /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T GetOrCreateUI <T>() where T : UIController, new() { var type = typeof(T); UIController uiBase = null; dict.TryGetValue(type, out uiBase); if (uiBase != null) { return(uiBase as T); } uiBase = new T(); uiBase.IsGameBaseUI = true; dict.Add(type, uiBase); var res_path = KResourceModule.GetAbFullPath($"ui/{uiBase.UITemplateName.ToLower()}"); var assetBundle = AssetBundle.LoadFromFile(res_path); Debuger.Assert(assetBundle != null, $"load ab error ,file:{res_path}"); var t = assetBundle.LoadAsset <GameObject>(uiBase.UITemplateName); GameObject uiObj = GameObject.Instantiate(t); //TODO 管理图集 if (uiObj) { var windowAsset = uiObj.GetComponent <UIWindowAsset>(); if (windowAsset && !string.IsNullOrEmpty(windowAsset.Atals_arr)) { string[] arr = windowAsset.Atals_arr.Split(','); int sprite_count = 0; for (int i = 0; i < arr.Length; i++) { string atlas_name = arr[i].ToLower(); if (!UIModule.Instance.CommonAtlases.Contains(atlas_name)) { sprite_count++; var atlas = assetBundle.LoadAsset <SpriteAtlas>(atlas_name); if (atlas != null) { ABManager.SpriteAtlases[atlas_name] = atlas; } } } if (sprite_count > windowAsset.MAX_Atlas) { Log.LogError($"UI:{uiBase.UITemplateName}包括过多图集({windowAsset.Atals_arr})会减慢加载速度,请处理"); } } } assetBundle.Unload(false); uiBase.gameObject = uiObj; uiBase.transform = uiObj.transform; uiBase.UIName = uiBase.UITemplateName; uiBase.OnInit(); return(uiBase as T); }
public override void OnInit() { base.OnInit(); Button1 = GetControl <Button>("Button1"); // child Debuger.Assert(Button1); HomeLabel = GetControl <Text>("HomeText"); Button1.onClick.AddListener(() => Logger.LogWarning("Click Home Button!")); }
public AvatarActionImageAnimation GetAvatarActionImageAnimation(string action) { AvatarActionImageAnimation animation = null; if (!actions.TryGetValue(action, out animation)) { animation = null; } Debuger.Assert(animation); return(animation); }
/// <summary> /// Default load setting strategry, editor load file, runtime resources.load /// </summary> /// <param name="path"></param> /// <returns></returns> public static byte[] DefaultLoadSetting(string path) { byte[] fileContent; var loader = HotBytesLoader.Load(SettingFolderName + "/" + path, LoaderMode.Sync); Debuger.Assert(!loader.IsError); fileContent = loader.Bytes; loader.Release(); return(fileContent); }
/// <summary> /// 等待并获取UI实例,执行callback /// 源起Loadindg UI, 在加载过程中,进度条设置方法会失效 /// 如果是DynamicWindow,,使用前务必先要Open! /// </summary> /// <param name="uiName"></param> /// <param name="callback"></param> /// <param name="args"></param> public void CallUI(string uiName, Action <UIController, object[]> callback, params object[] args) { Debuger.Assert(callback); UILoadState uiState; if (!UIWindows.TryGetValue(uiName, out uiState)) { uiState = LoadWindow(uiName, false); // 加载,这样就有UIState了, 但注意因为没参数,不要随意执行OnOpen } uiState.DoCallback(callback, args); }
protected void ProcessUITexture(string resourcePath) { LoadTexture(resourcePath, (_tex) => { if (!IsDestroy) { Debuger.Assert(DependencyComponent is UITexture); var uiTex = (UITexture)DependencyComponent; uiTex.mainTexture = _tex; // different pixelSize ! uiTex.pixelSize = GameDef.PictureScale; } OnFinishLoadDependencies(gameObject); // 返回GameObject而已哦 }); }
public static void MoveAllCollidersToGameObject(GameObject srcGameObject, GameObject targetGameObject) { Debuger.Assert(srcGameObject != targetGameObject); foreach (Collider collider2d in srcGameObject.GetComponentsInChildren <Collider>()) { CopyColliderToGameObject(collider2d, targetGameObject); GameObject.Destroy(collider2d); } foreach (Collider2D collider2d in srcGameObject.GetComponentsInChildren <Collider2D>()) { CopyCollider2DToGameObject(collider2d, targetGameObject); GameObject.Destroy(collider2d); } }
protected override void DoProcess(string resourcePath) { var loader = SpriteLoader.Load(resourcePath, (isOk, sprite) => { if (!IsDestroy) { var spriteRenderer = DependencyComponent as SpriteRenderer; Debuger.Assert(spriteRenderer); spriteRenderer.sprite = sprite; } OnFinishLoadDependencies(gameObject); // 返回GameObject而已哦 }); this.ResourceLoaders.Add(loader); }
/// <summary> /// Default load setting strategry, editor load file, runtime resources.load /// </summary> /// <param name="path"></param> /// <returns></returns> public static byte[] DefaultLoadSetting(string path) { //NOTE 在Editor下Reload 配置表失败 #if UNITY_EDITOR return(LoadSettingFromFile(path)); #else byte[] fileContent; var loader = HotBytesLoader.Load(SettingFolderName + "/" + path, LoaderMode.Sync); Debuger.Assert(!loader.IsError); fileContent = loader.Bytes; loader.Release(); return(fileContent); #endif }
/// <summary> /// DynamicWindow专用, 不会自动加载,会提示报错 /// </summary> /// <param name="uiName"></param> /// <param name="callback"></param> /// <param name="args"></param> public void CallDynamicUI(string uiName, Action <UIController, object[]> callback, params object[] args) { Debuger.Assert(callback); UILoadState uiState; if (!UIWindows.TryGetValue(uiName, out uiState)) { Log.Error("找不到UIState: {0}", uiName); return; } UILoadState openState = UIWindows[uiName]; openState.DoCallback(callback, args); }
/// <summary> /// 确保读取完 /// </summary> /// <param name="type"></param> private void EnsureLoad(Type type) { Debuger.Assert(typeof(CBaseInfo).IsAssignableFrom(type)); Func <string>[] getContentFuncs; if (LazyLoad.TryGetValue(type, out getContentFuncs)) { foreach (var func in getContentFuncs) { DoLoadTab(type, new[] { func() }); } LazyLoad.Remove(type); } }
protected bool ParseReader(TextReader oReader) { // 首行 var headLine = oReader.ReadLine(); Debuger.Assert(headLine != null); var defLine = oReader.ReadLine(); // 声明行 Debuger.Assert(defLine != null); var defLineArr = defLine.Split(KTabFileDef.Separators, StringSplitOptions.None); string[] firstLineSplitString = headLine.Split(KTabFileDef.Separators, StringSplitOptions.None); // don't remove RemoveEmptyEntries! string[] firstLineDef = new string[firstLineSplitString.Length]; Array.Copy(defLineArr, 0, firstLineDef, 0, defLineArr.Length); // 拷贝,确保不会超出表头的 for (int i = 1; i <= firstLineSplitString.Length; i++) { var headerString = firstLineSplitString[i - 1]; var headerInfo = new HeaderInfo { ColumnIndex = i, HeaderName = headerString, HeaderDef = firstLineDef[i - 1], }; ColIndex[headerInfo.HeaderName] = headerInfo; } ColCount = firstLineSplitString.Length; // 標題 // 读取内容 string sLine = ""; int rowIndex = 1; // 从第1行开始 while (sLine != null) { sLine = oReader.ReadLine(); if (sLine != null) { string[] splitString1 = sLine.Split(KTabFileDef.Separators, StringSplitOptions.None); TabInfo[rowIndex] = splitString1; rowIndex++; } } return(true); }
protected void ProcessAudioSource(string path) { AudioLoader.Load(path, (isOk, clip) => { if (!IsDestroy) { AudioSource src = DependencyComponent as AudioSource; Debuger.Assert(src); src.clip = clip; //src.Play(); // 特效进行Play, 不主动播放 src.Stop(); } OnFinishLoadDependencies(DependencyComponent); // 返回GameObject而已哦 }); }
private void Awake() { if (_Instance != null) { Debuger.Assert(_Instance == this); } //InvokeRepeating("CheckGcCollect", 0f, 3f); if (Debug.isDebugBuild) { Debug.LogFormat("ResourceManager ApplicationPath: {0}", ApplicationPath); Debug.LogFormat("ResourceManager ProductPathWithProtocol: {0}", ProductPathWithProtocol); Debug.LogFormat("ResourceManager ProductPathWithoutProtocol: {0}", ProductPathWithoutFileProtocol); Debug.LogFormat("ResourceManager DocumentResourcesPath: {0}", DocumentResourcesPath); Debug.LogFormat("================================================================================"); } }