Exemple #1
0
        public void UpdateIfNeeded()
        {
            if (string.IsNullOrEmpty(Path))
            {
                Debug.LogWarning(Maintainer.LogPrefix + "Can't update Asset since path is not set!");
                return;
            }

            /*if (Path.Contains("qwerty.unity"))
             * {
             *      Debug.Log(Path);
             * }*/

            fileInfo.Refresh();

            if (!fileInfo.Exists)
            {
                Debug.LogWarning(Maintainer.LogPrefix + "Can't update asset since file at path is not found:\n" + fileInfo.FullName + "\nAsset Path: " + Path);
                return;
            }

            ulong currentHash = 0;

            if (metaFileInfo == null)
            {
                metaFileInfo = new FileInfo(fileInfo.FullName + ".meta");
            }

            metaFileInfo.Refresh();
            if (metaFileInfo.Exists)
            {
                currentHash += (ulong)metaFileInfo.LastWriteTimeUtc.Ticks;
                currentHash += (ulong)metaFileInfo.Length;
            }

            currentHash += (ulong)fileInfo.LastWriteTimeUtc.Ticks;
            currentHash += (ulong)fileInfo.Length;

            if (lastHash == currentHash)
            {
                for (var i = dependenciesGUIDs.Length - 1; i > -1; i--)
                {
                    var guid = dependenciesGUIDs[i];
                    var path = AssetDatabase.GUIDToAssetPath(guid);
                    path = CSPathTools.EnforceSlashes(path);
                    if (!string.IsNullOrEmpty(path) && File.Exists(path))
                    {
                        continue;
                    }

                    ArrayUtility.RemoveAt(ref dependenciesGUIDs, i);
                    foreach (var referenceInfo in referencesInfo)
                    {
                        if (referenceInfo.assetInfo.GUID != guid)
                        {
                            continue;
                        }

                        ArrayUtility.Remove(ref referencesInfo, referenceInfo);
                        break;
                    }
                }

                if (!needToRebuildReferences)
                {
                    return;
                }
            }

            foreach (var referenceInfo in referencesInfo)
            {
                foreach (var info in referenceInfo.assetInfo.referencedAtInfoList)
                {
                    if (info.assetInfo != this)
                    {
                        continue;
                    }

                    ArrayUtility.Remove(ref referenceInfo.assetInfo.referencedAtInfoList, info);
                    break;
                }
            }

            lastHash = currentHash;

            needToRebuildReferences = true;
            Size = fileInfo.Length;

            referencesInfo    = new ReferenceInfo[0];
            dependenciesGUIDs = new string[0];

            var dependencies = new List <string>();

            if (SettingsKind == AssetSettingsKind.NotSettings)
            {
                var getRegularDependencies = true;

                /* pre-regular dependencies additions */

                if (Type == CSReflectionTools.assemblyDefinitionAssetType)
                {
                    if (Kind == AssetKind.Regular)
                    {
                        //TODO: check if bug 1020737 is fixed and this can be removed
                        dependencies.AddRange(GetAssetsReferencedFromAssemblyDefinition(Path));
                        getRegularDependencies = false;
                    }
                }

#if UNITY_2019_2_OR_NEWER
                if (Type == CSReflectionTools.assemblyDefinitionReferenceAssetType)
                {
                    if (Kind == AssetKind.Regular)
                    {
                        dependencies.AddRange(GetAssetsReferencedFromAssemblyDefinitionReference(Path));
                        getRegularDependencies = false;
                    }
                }
#endif

#if UNITY_2018_2_OR_NEWER
                // checking by name since addressables are in optional external package
                if (Type != null && Type.Name == "AddressableAssetGroup")
                {
                    var references = AddressablesReferenceFinder.Extract(Path);
                    if (references != null && references.Count > 0)
                    {
                        dependencies.AddRange(references);
                    }
                }
#endif

                /* regular dependencies additions */

                if (getRegularDependencies)
                {
                    dependencies.AddRange(AssetDatabase.GetDependencies(Path, false));
                }

                /* post-regular dependencies additions */

                if (Type == CSReflectionTools.spriteAtlasType)
                {
                    CSArrayTools.TryAddIfNotExists(ref dependencies, GetGetAssetsInFoldersReferencedFromSpriteAtlas(Path));
                }
            }
            else
            {
                dependencies.AddRange(GetAssetsReferencedInPlayerSettingsAsset(Path, SettingsKind));
            }

            // kept for debugging purposes

            /*if (Path.Contains("1.unity"))
             * {
             *      Debug.Log("1.unity non-recursive dependencies:");
             *      foreach (var reference in references)
             *      {
             *              Debug.Log(reference);
             *      }
             * }*/

            if (Type == CSReflectionTools.shaderType)
            {
                // below is an another workaround for dependencies not include #include-ed files, like *.cginc
                ScanFileForIncludes(dependencies, Path);
            }

            if (Type == CSReflectionTools.textAssetType && Path.EndsWith(".cginc"))
            {
                // below is an another workaround for dependencies not include #include-ed files, like *.cginc
                ScanFileForIncludes(dependencies, Path);
            }

            var guids = new string[dependencies.Count];

            for (var i = 0; i < dependencies.Count; i++)
            {
                guids[i] = AssetDatabase.AssetPathToGUID(dependencies[i]);
            }

            dependenciesGUIDs = guids;
        }
Exemple #2
0
    static public void Setup(string testType, string pathFormat, string suffix)
    {
#if UNITY_EDITOR
        bool currentIgnoreState = LogAssert.ignoreFailingMessages;
        LogAssert.ignoreFailingMessages = true;

        var RootFolder = string.Format(pathFormat, testType, suffix);

        Directory.CreateDirectory(RootFolder);

        var settings = AddressableAssetSettings.Create(RootFolder + "/Settings", "AddressableAssetSettings.Tests", false, true);
        var group    = settings.FindGroup("TestStuff" + suffix);

        if (group == null)
        {
            group = settings.CreateGroup("TestStuff" + suffix, true, false, false, null, typeof(BundledAssetGroupSchema));
        }
        settings.DefaultGroup = group;
        for (int i = 0; i < kPrefabCount; i++)
        {
            var guid  = CreateAsset(RootFolder + "/test" + i + suffix + ".prefab", "testPrefab" + i);
            var entry = settings.CreateOrMoveEntry(guid, group, false, false);
            entry.address = Path.GetFileNameWithoutExtension(entry.AssetPath);

            entry.SetLabel(GetPrefabLabel(suffix), true, false);
            entry.SetLabel(GetPrefabAlternatingLabel(suffix, i), true, false);
            entry.SetLabel(GetPrefabUniqueLabel(suffix, i), true, false);
        }

        var texture = new Texture2D(32, 32);
        var data    = ImageConversion.EncodeToPNG(texture);
        UnityEngine.Object.DestroyImmediate(texture);
        AssetDatabase.GenerateUniqueAssetPath(RootFolder);
        var spritePath = RootFolder + "sprite.png";
        File.WriteAllBytes(spritePath, data);

        AssetDatabase.ImportAsset(spritePath, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);

        var spriteGuid = AssetDatabase.AssetPathToGUID(spritePath);
        var importer   = (TextureImporter)AssetImporter.GetAtPath(spritePath);
        importer.textureType      = TextureImporterType.Sprite;
        importer.spriteImportMode = SpriteImportMode.Multiple;
        importer.spritesheet      = new SpriteMetaData[] { new SpriteMetaData()
                                                           {
                                                               name = "topleft", pivot = Vector2.zero, rect = new Rect(0, 0, 16, 16)
                                                           },
                                                           new SpriteMetaData()
                                                           {
                                                               name = "botright", pivot = Vector2.zero, rect = new Rect(16, 16, 16, 16)
                                                           } };
        importer.SaveAndReimport();

        var spriteEntry = settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(spritePath), group, false, false);
        spriteEntry.address = "sprite";

        var so  = ScriptableObject.CreateInstance <TestObject>();
        var sub = ScriptableObject.CreateInstance <TestObject>();
        sub.name = "sub";
        AssetDatabase.CreateAsset(so, RootFolder + "sub.asset");
        AssetDatabase.AddObjectToAsset(sub, RootFolder + "sub.asset");
        AssetDatabase.ImportAsset(RootFolder + "sub.asset", ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
        var        subGuid      = AssetDatabase.AssetPathToGUID(RootFolder + "sub.asset");
        string     assetRefGuid = CreateAsset(RootFolder + "/testIsReference.prefab", "IsReference");
        GameObject go           = new GameObject("AssetReferenceBehavior");
        AssetReferenceTestBehavior aRefTestBehavior = go.AddComponent <AssetReferenceTestBehavior>();
        aRefTestBehavior.Reference = settings.CreateAssetReference(assetRefGuid);
        aRefTestBehavior.ReferenceWithSubObject = settings.CreateAssetReference(subGuid);
        aRefTestBehavior.ReferenceWithSubObject.SubObjectName = "sub";
        aRefTestBehavior.LabelReference = new AssetLabelReference()
        {
            labelString = settings.labelTable.labelNames[0]
        };

        string hasBehaviorPath = RootFolder + "/AssetReferenceBehavior.prefab";
        PrefabUtility.SaveAsPrefabAsset(go, hasBehaviorPath);
        settings.CreateOrMoveEntry(AssetDatabase.AssetPathToGUID(hasBehaviorPath), group, false, false);
        //AssetDatabase.StopAssetEditing();
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);

        RunBuilder(settings, testType, suffix);
        LogAssert.ignoreFailingMessages = currentIgnoreState;
#endif
    }
Exemple #3
0
    void Listmat()
    {
        string path = Application.dataPath;

        MaterialPath    = new List <string>(Directory.GetFiles(path, "*.mat", SearchOption.AllDirectories));
        PrefabPath      = new List <string>(Directory.GetFiles(path, "*.prefab", SearchOption.AllDirectories));
        Checkshaderpath = new List <string>();
        PrefabQuotePath = new List <string>();

        Shader shaderpath = (Shader.Find(shadername));
        string shaderguid = AssetDatabase.GetAssetPath(shaderpath);

        guid01 = AssetDatabase.AssetPathToGUID(shaderguid); //获取shaderGUID

        for (int i = 0; i < MaterialPath.Count; i++)
        {
            string filepath = MaterialPath[i];


            if (Regex.IsMatch(File.ReadAllText(filepath), guid01))
            {
                Checkshaderpath.Add(MaterialPath[i]);

                string   matpath  = MaterialPath[i];
                string[] matArray = matpath.Split('/');
                string   path01   = matArray[matArray.Length - 1];
                string   matguid  = AssetDatabase.AssetPathToGUID(path01);

                for (int t = 0; t < PrefabPath.Count; t++)
                {
                    string prefabfilepath = PrefabPath[t];
                    if (Regex.IsMatch(File.ReadAllText(prefabfilepath), matguid))
                    {
                        PrefabQuotePath.Add(PrefabPath[t]);
                        //Debug.LogWarning(PrefabPath[t] + "引用了" + path01);

                        string   prefabpathstring = PrefabPath[t];
                        string[] prefabArray      = prefabpathstring.Split('/');
                        string   path02           = prefabArray[prefabArray.Length - 1];
                        string[] PFchildname      = path02.Split(new char[2] {
                            '.', '\\'
                        });
                        string   childname        = PFchildname[PFchildname.Length - 2];
                        string[] childname01Array = childname.Split('_');
                        string   childname02      = childname01Array[0];

                        GameObject thisloadprefab = AssetDatabase.LoadAssetAtPath <GameObject>(path02);
                        // Debug.Log(childname02);
                        Vector3 prefabscale = thisloadprefab.transform.GetChild(0).gameObject.transform.localScale;
                        if (prefabscale != null)
                        {
                            Material thismat = AssetDatabase.LoadAssetAtPath <Material>(path01);
                            thismat.SetFloat(ShaderProperties, prefabscale.x * OutLineScale);
                        }
                        else
                        {
                            Debug.LogError("未找到子对象");
                        }
                    }
                    else
                    {
                        //  Debug.LogWarning("没有找到" + MaterialPath[i]+"关联的prefab");
                    }
                }
                //Debug.LogWarning("shader关联材质matGUID:" + matguid);
            }
        }
    }
        public void Update(List <LiveLinkChangeSet> changeSets, NativeList <Hash128> loadScenes, NativeList <Hash128> unloadScenes, LiveLinkMode mode)
        {
            if (_LoadedScenes.Count == 0 && _SceneGUIDToLiveLink.Count == 0 && _RemovedScenes.Length == 0)
            {
                return;
            }

            // If build configuration changed, we need to trigger a full conversion
            if (_BuildConfigurationGUID != default)
            {
                // TODO: Allocs, needs better API
                var buildConfigurationDependencyHash = AssetDatabase.GetAssetDependencyHash(AssetDatabase.GUIDToAssetPath(_BuildConfigurationGUID.ToString()));
                if (_BuildConfigurationArtifactHash != buildConfigurationDependencyHash)
                {
                    _BuildConfigurationArtifactHash = buildConfigurationDependencyHash;
                    RequestCleanConversion();
                }
            }

            if (_PreviousGlobalDirtyID != GlobalDirtyID)
            {
                RequestCleanConversion();
                _PreviousGlobalDirtyID = GlobalDirtyID;
            }

            // By default all scenes need to have m_GameObjectSceneCullingMask, otherwise they won't show up in game view
            _GUIDToEditScene.Clear();
            for (int i = 0; i != EditorSceneManager.sceneCount; i++)
            {
                var scene     = EditorSceneManager.GetSceneAt(i);
                var sceneGUID = new GUID(AssetDatabase.AssetPathToGUID(scene.path));

                if (_LoadedScenes.Contains(sceneGUID))
                {
                    if (scene.isLoaded && sceneGUID != default(GUID))
                    {
                        _GUIDToEditScene.Add(sceneGUID, scene);
                    }
                }
            }

            foreach (var scene in _SceneGUIDToLiveLink)
            {
                if (!_GUIDToEditScene.ContainsKey(scene.Key))
                {
                    unloadScenes.Add(scene.Key);
                }
            }

            // Process scenes that are no longer loaded
            foreach (var scene in unloadScenes)
            {
                var liveLink = _SceneGUIDToLiveLink[scene];
                liveLink.Dispose();
                _SceneGUIDToLiveLink.Remove(scene);
                _SentLoadScenes.Remove(scene);
            }
            foreach (var scene in _RemovedScenes)
            {
                if (_SceneGUIDToLiveLink.TryGetValue(scene, out var liveLink))
                {
                    liveLink.Dispose();
                    _SceneGUIDToLiveLink.Remove(scene);
                }

                unloadScenes.Add(scene);
                _SentLoadScenes.Remove(scene);
            }
            _RemovedScenes.Clear();

            _SentLoadScenes.RemoveWhere(scene => !_LoadedScenes.Contains(scene));

            // Process all scenes that the player needs
            foreach (var sceneGuid in _LoadedScenes)
            {
                var isLoaded = _GUIDToEditScene.TryGetValue(sceneGuid, out var scene);

                // We are editing with live link. Ensure it is active & up to date
                if (isLoaded)
                {
                    var liveLink = GetLiveLink(sceneGuid);
                    if (liveLink == null || liveLink.DidRequestUpdate() || liveLink.LiveLinkDirtyID != GetSceneDirtyID(scene))
                    {
                        AddLiveLinkChangeSet(sceneGuid, changeSets, mode);
                    }
                }
                else
                {
                    if (_SentLoadScenes.Add(sceneGuid))
                    {
                        loadScenes.Add(sceneGuid);
                    }
                }
            }
        }
        /// <summary> Copies the file into the resources folder. Naming the new asset to KEY </summary>
        public static string CopyFileIntoResources(SerializableLocalizationObjectPair objectPair, SmartCultureInfo thisCultureInfo)
        {
            if (!DirectoryUtility.CheckAndCreate(LocalizationWorkspace.LanguageRuntimeFolderPath(thisCultureInfo.languageCode)))
            {
                return("");
            }


            string          newFileName      = objectPair.keyValue;
            string          filePath         = string.Empty;
            string          currentAssetPath = string.Empty;
            LocalizedObject objectToCopy     = objectPair.changedValue;

            if (objectToCopy.ObjectType == LocalizedObjectType.AUDIO && objectToCopy.ThisAudioClip != null)
            {
                filePath         = LocalizationWorkspace.LanguageAudioFolderPath(thisCultureInfo.languageCode);
                currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisAudioClip);
            }
            else if (objectToCopy.ObjectType == LocalizedObjectType.TEXTURE && objectToCopy.ThisTexture != null)
            {
                filePath         = LocalizationWorkspace.LanguageTexturesFolderPath(thisCultureInfo.languageCode);
                currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisTexture);
            }
            else if (objectToCopy.ObjectType == LocalizedObjectType.GAME_OBJECT && objectToCopy.ThisGameObject != null)
            {
                filePath         = LocalizationWorkspace.LanguagePrefabsFolderPath(thisCultureInfo.languageCode);
                currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisGameObject);
            }
            else if (objectToCopy.ObjectType == LocalizedObjectType.TEXT_ASSET && objectToCopy.ThisTextAsset != null)
            {
                filePath         = LocalizationWorkspace.LanguageTextAssetsFolderPath(thisCultureInfo.languageCode);
                currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisTextAsset);
            }
            else if (objectToCopy.ObjectType == LocalizedObjectType.FONT && objectToCopy.Font != null)
            {
                filePath         = LocalizationWorkspace.LanguageFontsFolderPath(thisCultureInfo.languageCode);
                currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.Font);
            }
            else
            {
                return(string.Empty);
            }

            if (!DirectoryUtility.CheckAndCreate(filePath))
            {
                return("");
            }

            //Get the fileExtension of the asset
            string fileExtension = FileUtility.GetFileExtension(Application.dataPath + currentAssetPath);

            if (objectToCopy.ObjectType != LocalizedObjectType.GAME_OBJECT)
            {
                //Copy or replace the file to the new path
                FileUtil.ReplaceFile(currentAssetPath, filePath + "/" + newFileName + fileExtension);

                string metaFile = Application.dataPath.Substring(0, Application.dataPath.Length - "Assets".Length) +
                                  currentAssetPath.Substring(0, currentAssetPath.Length - fileExtension.Length) + fileExtension + ".meta";
                if (File.Exists(metaFile))
                {
                    FileUtil.ReplaceFile(metaFile, filePath + "/" + newFileName + fileExtension + ".meta");
                }
            }
            else
            {
                string relativePath = filePath + "/" + newFileName + fileExtension;
                relativePath = "Assets" + relativePath.Substring(Application.dataPath.Length);
                //1PrefabUtility.CreatePrefab(relativePath, objectToCopy.ThisGameObject);
                PrefabUtility.SaveAsPrefabAsset(objectToCopy.ThisGameObject, relativePath);             // TODO Перепроверить
            }

            return(AssetDatabase.AssetPathToGUID(currentAssetPath));
        }
Exemple #6
0
 static bool IsSpriteMesh(string assetPath)
 {
     return(s_SpriteMeshToTextureCache.ContainsKey(AssetDatabase.AssetPathToGUID(assetPath)));
 }
        public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged)
        {
            if (m_loadPath == null)
            {
                return;
            }

            EditorGUILayout.HelpBox("Load From Directory: Load assets from given directory path.", MessageType.Info);
            editor.UpdateNodeName(node);

            GUILayout.Space(10f);

            bool bRespondAP = EditorGUILayout.ToggleLeft("Respond To Asset Change", m_respondToAssetChange);

            if (bRespondAP != m_respondToAssetChange)
            {
                using (new RecordUndoScope("Remove Target Load Path Settings", node, true)) {
                    m_respondToAssetChange = bRespondAP;
                }
            }

            GUILayout.Space(4f);

            //Show target configuration tab
            editor.DrawPlatformSelector(node);
            using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
                var disabledScope = editor.DrawOverrideTargetToggle(node, m_loadPath.ContainsValueOf(editor.CurrentEditingGroup), (bool b) => {
                    using (new RecordUndoScope("Remove Target Load Path Settings", node, true)) {
                        if (b)
                        {
                            m_loadPath[editor.CurrentEditingGroup]     = m_loadPath.DefaultValue;
                            m_loadPathGuid[editor.CurrentEditingGroup] = m_loadPathGuid.DefaultValue;
                        }
                        else
                        {
                            m_loadPath.Remove(editor.CurrentEditingGroup);
                            m_loadPathGuid.Remove(editor.CurrentEditingGroup);
                        }
                        onValueChanged();
                    }
                });

                using (disabledScope) {
                    var path = m_loadPath[editor.CurrentEditingGroup];
                    EditorGUILayout.LabelField("Load Path:");

                    string newLoadPath = null;

                    newLoadPath = editor.DrawFolderSelector(Model.Settings.Path.ASSETS_PATH, "Select Asset Folder",
                                                            path,
                                                            FileUtility.PathCombine(Model.Settings.Path.ASSETS_PATH, path),
                                                            (string folderSelected) => { return(NormalizeLoadPath(folderSelected)); }
                                                            );

                    var dirPath = Path.Combine(Model.Settings.Path.ASSETS_PATH, newLoadPath);

                    if (newLoadPath != path)
                    {
                        using (new RecordUndoScope("Load Path Changed", node, true)){
                            m_loadPath[editor.CurrentEditingGroup]      = newLoadPath;
                            m_loadPathGuid [editor.CurrentEditingGroup] = AssetDatabase.AssetPathToGUID(dirPath);
                            onValueChanged();
                        }
                    }

                    bool dirExists = Directory.Exists(dirPath);

                    GUILayout.Space(10f);

                    using (new EditorGUILayout.HorizontalScope()) {
                        using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(newLoadPath) || !dirExists))
                        {
                            GUILayout.FlexibleSpace();
                            if (GUILayout.Button("Highlight in Project Window", GUILayout.Width(180f)))
                            {
                                // trailing is "/" not good for LoadMainAssetAtPath
                                if (dirPath[dirPath.Length - 1] == '/')
                                {
                                    dirPath = dirPath.Substring(0, dirPath.Length - 1);
                                }
                                var obj = AssetDatabase.LoadMainAssetAtPath(dirPath);
                                EditorGUIUtility.PingObject(obj);
                            }
                        }
                    }

                    if (!dirExists)
                    {
                        var  parentDirPath   = Path.GetDirectoryName(dirPath);
                        bool parentDirExists = Directory.Exists(parentDirPath);
                        if (parentDirExists)
                        {
                            EditorGUILayout.LabelField("Available Directories:");
                            string[] dirs = Directory.GetDirectories(parentDirPath);
                            foreach (string s in dirs)
                            {
                                EditorGUILayout.LabelField(s);
                            }
                        }
                    }
                }
            }

            GUILayout.Space(8f);
            DrawIgnoredPatterns(node, onValueChanged);
        }
Exemple #8
0
        public static void SetUp()
        {
            s_Assets.SetUp();

            var assetGuids = new List<GUID>();
            try
            {
                {
                    string path = s_Assets.GetNextPath(".asset");
                    AssetDatabase.CreateAsset(s_TempTexture = new Texture2D(64, 64), path);
                    s_TempTextureGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                    assetGuids.Add(s_TempTextureGuid);
                }
                {
                    string path = s_Assets.GetNextPath(".mat");
                    AssetDatabase.CreateAsset(s_TempMaterial = new Material(Shader.Find("Standard")), path);
                    s_TempMaterialGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                    assetGuids.Add(s_TempMaterialGuid);
                    s_TempMaterial.mainTexture = s_TempTexture;
                }

                var tempScenePath = s_Assets.GetNextPath(".unity");
                s_TempScene = SubSceneTestsHelper.CreateScene(tempScenePath);
                s_SubSceneWithSections = SubSceneTestsHelper.CreateSubSceneInSceneFromObjects("SubScene", false, s_TempScene, () =>
                {
                    var go1 = new GameObject();
                    go1.AddComponent<SceneSectionComponent>().SectionIndex = 0;
                    var go2 = new GameObject();
                    go2.AddComponent<SceneSectionComponent>().SectionIndex = 2;
                    go2.AddComponent<TestComponentAuthoring>().Material = s_TempMaterial;
                    return new List<GameObject> { go1, go2 };
                });

                {
                    var path = s_Assets.GetNextPath("LiveLinkBuildConfig.buildconfiguration");
                    BuildConfiguration.CreateAsset(path, config =>
                    {
                        config.SetComponent(new SceneList
                        {
                            SceneInfos = new List<SceneList.SceneInfo>
                            {
                                new SceneList.SceneInfo
                                {
                                    Scene = GlobalObjectId.GetGlobalObjectIdSlow(AssetDatabase.LoadAssetAtPath<SceneAsset>(tempScenePath))
                                }
                            }
                        });
                    });
                    s_LiveLinkBuildConfigGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                }
            }
            catch
            {
                s_Assets.TearDown();
                throw;
            }

            // This call ensures that the asset worker is already running and no test times out because we're still
            // waiting for the asset worker. Effectively this doesn't change the runtime that much since we will have
            // to wait for the import to finish in most of the tests anyway.
            GeEntitySceneArtifactHash(s_SubSceneWithSections.SceneGUID, s_LiveLinkBuildConfigGuid, ImportMode.Synchronous);

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            s_TempAssetGuids = assetGuids.ToArray();
            DefaultWorldInitialization.DefaultLazyEditModeInitialize();
            s_Connection = new LiveLinkTestConnection();
            EditorSceneLiveLinkToPlayerSendSystem.instance.SetConnection(s_Connection);
            LiveLinkAssetBundleBuildSystem.instance.SetConnection(s_Connection);
        }
Exemple #9
0
    public static void AllReferenceFindResource()
    {
        EditorSettings.serializationMode = SerializationMode.ForceText;

        string fullDir = Application.dataPath + "/" + dirpath;
        var    notwithhoutExtensions = new List <string>()
        {
            ".meta"
        };

        // 需要反向查找的资源
        string[] files = Directory.GetFiles(fullDir, "*.*", SearchOption.AllDirectories)
                         .Where(s => !notwithhoutExtensions.Contains(Path.GetExtension(s).ToLower())).ToArray();

        // 目标资源
        var targetExtensions = new List <string>()
        {
            ".prefab", ".unity", ".fbx", ".mat", ".asset"
        };

        string[] targetFiles = Directory.GetFiles(Application.dataPath + "/ModelTest", "*.*", SearchOption.AllDirectories)
                               .Where(s => targetExtensions.Contains(Path.GetExtension(s).ToLower())).ToArray();


        int startIndex = 0;

        //EditorApplication.update = delegate()
        {
            for (int i = 0; i < files.Length; i++)
            {
                string assetpath = files[i].Replace("\\", "/").Replace(Application.dataPath, "Assets");

                string guid = AssetDatabase.AssetPathToGUID(assetpath);
                Debug.Log(guid);
                for (int j = 0; j < targetFiles.Length; j++)
                {
                    string _target = targetFiles[j];

                    bool   isCancel = EditorUtility.DisplayCancelableProgressBar("资源匹配中", _target, (float)startIndex / (float)targetFiles.Length);
                    string txt      = File.ReadAllText(_target);
                    Debug.Log(txt);
                    if (Regex.IsMatch(txt /*File.ReadAllText(_target)*/, guid))
                    {
                        Debug.LogError(guid);
                        string   taregtpath = _target.Replace("\\", "/").Replace(Application.dataPath + "/", "");
                        string[] shield     = taregtpath.Split('/');
                        if (shield.Length > 0)
                        {
                            if (!shieldDir.Contains(shield[0]))
                            {
                                Debug.Log(assetpath.Replace("Assets/", "") + "-->>  " + _target.Replace("\\", "/").Replace(Application.dataPath + "/", "") + ": ");
                            }
                        }
                        else
                        {
                            Debug.Log(assetpath.Replace("Assets/", "") + "-->>  " + _target.Replace("\\", "/").Replace(Application.dataPath + "/", "") + ": ");
                        }
                    }
                    if (isCancel)
                    {
                        //EditorUtility.ClearProgressBar();
                        //EditorApplication.update = null;
                        Debug.Log("匹配结束  匹配数量: " + startIndex + "  总数量: " + targetFiles.Length);
                        startIndex = 0;
                        break;
                    }
                }
            }

            EditorUtility.ClearProgressBar();
            //EditorApplication.update = null;
        };
    }
Exemple #10
0
        private void Generate()
        {
            var file = File.ReadAllText(Application.dataPath.Replace("Assets", string.Empty) + AssetDatabase.GetAssetPath(shaderFile));

            var regex = new Regex("(?<=(properties)).*?(?=(subshader))", RegexOptions.Singleline | RegexOptions.IgnoreCase);

            var match = regex.Match(file).Value;

            if (string.IsNullOrEmpty(match))
            {
                return;
            }

            var lines = match
                        .Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)
                        .Select(x => x.Trim().Trim('\t'))
                        .Where(x => !string.IsNullOrEmpty(x) && !x.StartsWith("/") && x.Length > 4);

            var attrebutes = new List <ShaderPropertyAttrebute>();

            var attrebuteTemp = new List <ShaderPropertyAttrebute>();

            foreach (var line in lines)
            {
                var attrebute = ShaderPropertyAttrebute.ParseToAttrebute(line);

                if (string.IsNullOrEmpty(attrebute.Name))
                {
                    attrebuteTemp.Add(attrebute);
                }
                else
                {
                    attrebuteTemp.Select(x =>
                    {
                        return(x.GetType().GetProperties()
                               .Where(y => !y.Name.Contains("Name"))
                               .Select(y =>
                        {
                            var value = y.GetValue(x, null);
                            if (Equals(value, null) || Equals(value, false))
                            {
                                return y;
                            }

                            attrebute.GetType().GetProperties().First(z => z.Name == y.Name).SetValue(attrebute, value, null);
                            return y;
                        })
                               .ToList());
                    })
                    .ToList();
                    attrebutes.Add(attrebute);
                    attrebuteTemp.Clear();
                }
            }

            var predicate = new Func <ShaderPropertyAttrebute, bool>(x => !x.HasHideInInspector && !x.HasPerRendererData);

            var maxVariableLength = attrebutes
                                    .Where(predicate)
                                    .Max(x => x.Name.Length);

            var fields = attrebutes
                         .Where(predicate)
                         .Select(x =>
            {
                var camelVariable = x.Name.ToCamelCase();
                var castResult    = 0;
                camelVariable     = int.TryParse(camelVariable.First().ToString(), out castResult)
                        ? camelVariable.Remove(0, 1)
                        : camelVariable;
                return(string.Format
                       (
                           "private readonly string {0}{1}= \"_{2}\"; ",
                           camelVariable,
                           "".AppendIndent(maxVariableLength - camelVariable.Length),
                           x.Name
                       ).AppendIndent(4));
            }).ToList();

            var foldFields = attrebutes
                             .Where(x => x.HasHeader)
                             .Select(x =>
            {
                var camelVariable = x.Name.ToCamelCase();
                var castResult    = 0;
                camelVariable     = int.TryParse(camelVariable.First().ToString(), out castResult)
                        ? camelVariable.Remove(0, 1)
                        : camelVariable;
                return(string.Format("private bool {0}Fold = false;", camelVariable).AppendIndent(4));
            })
                             .ToList();

            var headers = attrebutes.Where(x => x.HasHeader).Select(x => x.Header);

            var toggleFields = attrebutes
                               .Where(x => x.Name.ToLower().Contains("use")
//                            && headers.Any(y => y.ToLower().Contains(x.Name.ToLower().Replace("use", string.Empty)))
                                      )
                               .Select(x =>
            {
                var camelVariable = x.Name.ToCamelCase();
                var castResult    = 0;
                camelVariable     = int.TryParse(camelVariable.First().ToString(), out castResult)
                        ? camelVariable.Remove(0, 1)
                        : camelVariable;
                return(new
                {
                    Field = string.Format("private bool {0}Toggle = true;", camelVariable).AppendIndent(4),
                    Variable = string.Format("{0}Toggle", camelVariable),
                    PropertyName = x.Name
                });
            })
                               .ToList();

            fields.AddRange(foldFields);
            fields.AddRange(toggleFields.Select(x => x.Field));

            var template = File.ReadAllText(Application.dataPath.Replace("Assets", string.Empty) + AssetDatabase.GetAssetPath(templateFile));

            var fieldsArray = fields.ToArray();

            template = template.Replace("<#fields#>", string.Join(Environment.NewLine, fieldsArray));

            var inFold            = false;
            var propertyFoldGroup = string.Empty;
            var properties        = new List <string>();

            var attrebuteProps = attrebutes
                                 .Where(predicate)
                                 .Select(x =>
            {
                var camelVariable = x.Name.ToCamelCase();
                var castResult    = 0;
                camelVariable     = int.TryParse(camelVariable.First().ToString(), out castResult)
                        ? camelVariable.Remove(0, 1)
                        : camelVariable;
                return(new
                {
                    Attrebute = x,
                    FindProperty = string.Format
                                   (
                        "var {0}Prop {1}= FindProperty(this.{0}, properties, false);",
                        camelVariable,
                        "".AppendIndent(maxVariableLength - camelVariable.Length)
                                   ).AppendIndent(8),
                    PropertyVariable = string.Format("{0}Prop", camelVariable)
                });
            })
                                 .ToList();

            var findProps = string.Join(Environment.NewLine, attrebuteProps.Select(x => x.FindProperty).ToArray());

            template = template.Replace("<#findProps#>", findProps);

            var setKeywords = toggleFields
                              .Select(x => string.Format("UiUtils.SetKeyword({0}Prop, this.{1});", x.PropertyName.ToCamelCase(), x.Variable).AppendIndent(12))
                              .ToArray();

            template = template.Replace("<#setKeywords#>", string.Join(Environment.NewLine, setKeywords));

            var initializeToggles = toggleFields
                                    .Select(x => string.Format("this.{0} = {1}Prop.floatValue > 0;", x.Variable, x.PropertyName.ToCamelCase()).AppendIndent(16))
                                    .ToArray();

            template = template.Replace("<#initialToggle#>", string.Join(Environment.NewLine, initializeToggles));

            foreach (var toggleField in toggleFields)
            {
                attrebuteProps.RemoveAll(x => x.Attrebute.Name.Contains(toggleField.PropertyName));
            }

            foreach (var attrebute in attrebuteProps)
            {
                var camelVariable = attrebute.Attrebute.Name.ToCamelCase();
                var castResult    = 0;
                camelVariable = int.TryParse(camelVariable.First().ToString(), out castResult)
                    ? camelVariable.Remove(0, 1)
                    : camelVariable;
                if (attrebute.Attrebute.HasHeader)
                {
                    if (inFold)
                    {
                        propertyFoldGroup += string.Format("}});{0}{0}", Environment.NewLine).AppendIndent(12);
                    }

                    var toggle = toggleFields.FirstOrDefault(x => attrebute.Attrebute.Header.ToLower().Contains(x.PropertyName.ToLower().Replace("use", string.Empty)));
                    if (toggle == null)
                    {
                        propertyFoldGroup += string.Format
                                             (
                            "UiUtils.PropertyFoldGroup(\"{0}\", ref this.{1}Fold, () => {2}",
                            attrebute.Attrebute.Header,
                            camelVariable,
                            Environment.NewLine
                                             ).AppendIndent(12);
                    }
                    else
                    {
                        propertyFoldGroup += string.Format
                                             (
                            "UiUtils.PropertyToggleFoldGroup(\"{0}\", ref this.{1}Fold, ref this.{2}, () => {3}",
                            attrebute.Attrebute.Header,
                            camelVariable,
                            toggle.Variable,
                            Environment.NewLine
                                             ).AppendIndent(12);
                    }

                    propertyFoldGroup += string.Format("{{{0}", Environment.NewLine).AppendIndent(12);
                    inFold             = true;
                }

                if (attrebute.Attrebute.HasNoScaleOffset)
                {
                    propertyFoldGroup += string.Format
                                         (
                        "materialEditor.TexturePropertySingleLine(new GUIContent(\"{0}\"), {1}); ",
                        attrebute.Attrebute.DisplayName,
                        attrebute.PropertyVariable
                                         ).AppendIndent(16) + Environment.NewLine;
                }
                else if (attrebute.Attrebute.IsTexture)
                {
                    propertyFoldGroup += string.Format
                                         (
                        "materialEditor.ShaderProperty({0}, \"{1}\");",
                        attrebute.PropertyVariable,
                        attrebute.Attrebute.DisplayName
                                         ).AppendIndent(16) + Environment.NewLine;
                }
                else
                {
                    propertyFoldGroup += string.Format
                                         (
                        "materialEditor.ShaderProperty({0}, \"{1}\");",
                        attrebute.PropertyVariable,
                        attrebute.Attrebute.DisplayName
                                         ).AppendIndent(16) + Environment.NewLine;
                }
            }

            if (inFold)
            {
                propertyFoldGroup += string.Format("}});{0}{0}", Environment.NewLine).AppendIndent(12);
            }

            template = template.Replace("<#propGroup#>", propertyFoldGroup);

            template = template.Replace("<#=generatorName#>", "ShaderPropertyGenerator");
            template = template.Replace("<#=dateTimeNow#>", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            template = template.Replace("<#=className#>", className.ToPascalCase());
            template = template.Replace("<#=guid#>", AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(shaderFile)));

            Directory.CreateDirectory(Application.dataPath.Replace("Assets", string.Empty) + "/Editor/");

            File.WriteAllText(Application.dataPath + "/Editor/" + className.ToPascalCase() + ".cs", template);

            AssetDatabase.Refresh();
        }
    static void SetDiffBuilds()
    {
        mBuildsList = new List <AssetBundleBuild>();
        mClearList  = new List <AssstCaheData>();
        var isNeedPack = false;
        var cacheList  = new List <string>();

        if (mCacheAssetBund != null)
        {
            cacheList = mCacheAssetBund.Keys.ToList();
        }

        foreach (var build in tempBuilds.Values)
        {
            isNeedPack = false;
            //差异化判断,如果没缓存表,就打包全部资源
            if (mCacheAssetBund != null)
            {
                var abName = build.assetBundleName;
                //如果缓存表存在AB包的key,开始检查缓存的与需要打包资源的差异
                if (mCacheAssetBund.ContainsKey(abName))
                {
                    //从缓存list中删除,如果删到最后list不为空,则说明资源需要删除
                    cacheList.Remove(abName);
                    var cache = mCacheAssetBund[abName];
                    //    Debug.Log(abName + "=> hash " + cache.md5);
                    //如何缓存的guid列表存在,则继续比较差异,如果不存在说明需要打包
                    if (cache.mGuilds != null)
                    {
                        var guids = cache.mGuilds.Keys.ToList();
                        //比对缓存的ab包和要打包的ab包的文件差异
                        foreach (var path in build.assetNames)
                        {
                            var guid = AssetDatabase.AssetPathToGUID(path);
                            var hash = AssetDatabase.GetAssetDependencyHash(path).ToString();
                            if (guids.Contains(guid))
                            {
                                guids.Remove(guid);
                                var cacheHash = cache.mGuilds[guid];
                                if (cacheHash != hash)
                                {
                                    Debug.LogError(abName + "hash 发生改变!old" + cacheHash + " cur " + hash);
                                    isNeedPack = true;
                                    break;
                                }
                            }
                            else
                            {
                                Debug.LogError(guid + "缓存不包括此guids!" + path);

                                isNeedPack = true;
                                break;
                            }
                        }
                        //如果取完build的path的keys发现还有缓存的,说明缓存的文件比要打包的文件多,需要重新打包
                        if (guids.Count > 0)
                        {
                            Debug.LogError("取完build的path的keys发现还有缓存的,需要重新打包==> 剩余guids Count" + guids.Count);

                            isNeedPack = true;
                        }
                    }
                    else
                    {
                        Debug.LogError("hashs 没有值直接需要打包");

                        isNeedPack = true;
                    }
                    if (isNeedPack)
                    {
                        mClearList.Add(cache);
                    }
                }
                else
                {
                    Debug.Log(abName + "=> 没有缓存需要重新打包 ");
                    isNeedPack = true;
                }
            }
            else
            {
                Debug.Log("CacheAssetBund 没有值需要重新打包 ");
                isNeedPack = true;
            }

            if (isNeedPack)
            {
                Debug.LogError("Is NeedPack item: " + build.assetBundleName + " count " + build.assetNames.Count);
                foreach (var path in build.assetNames)
                {
                    Debug.LogError("item Path: " + path);
                }
                mBuildsList.Add(build.GetAssetBundleBuild());
            }
            else
            {
                //    Debug.Log("Not NeedPack item: " + build.assetBundleName + " count " + build.assetNames.Count);
            }
        }
        if (cacheList.Count > 0)
        {
            foreach (var abName in cacheList)
            {
                var cache = mCacheAssetBund[abName];
                Debug.LogError(abName + "已经不需要,添加删除!");
                mClearList.Add(cache);
            }
        }
        Debug.Log(" 需要打包的数量 " + mBuildsList.Count);
    }
Exemple #12
0
        void PostProcessMeta()
        {
            #region Repair GUIDS
            bool refresh = false;
            foreach (var a in scriptAbsPathToGuid)
            {
                // Get latest guid of script from assetdatabase and compare to cached to see if changed
                string newGuid = AssetDatabase.AssetPathToGUID(SmartEditorUtils.ToRelativePath(a.Key));
                if (newGuid != a.Value)
                {
                    Debug.LogWarningFormat("Repairing changed GUID for script {0}", a.Key);
                    string metaPath = a.Key + ".meta";

                    #region Repair meta file
                    if (File.Exists(metaPath))
                    {
                        // Find line with latest guid and replace with cached guid
                        var lines = File.ReadAllLines(a.Key);
                        for (int i = 0; i < lines.Length; ++i)
                        {
                            string l = lines[i];
                            if (l.Contains(newGuid))
                            {
                                Debug.LogFormat("\n\tRestoring {0} to {1}", newGuid, a.Value);
                                lines[i] = l.Replace(newGuid, a.Value);

                                // Save and flag for asset database refresh
                                File.WriteAllLines(a.Key, lines);
                                refresh = true;
                                break;
                            }
                        }
                    }
                    #endregion
                }
            }
            if (refresh)
            {
                AssetDatabase.Refresh();
            }
            #endregion

            #region Set icons
            refresh = false;
            foreach (var a in scriptAbsPathToGuid)
            {
                string metaPath = a.Key + ".meta";
                if (File.Exists(metaPath))
                {
                    var lines = File.ReadAllLines(metaPath);

                    // Read meta file, look for line with "icon:"
                    for (int i = 0; i < lines.Length; ++i)
                    {
                        string l = lines[i];

                        // Line must have "icon: " and default icon stuff
                        if (l.Contains(ICON_MATCH))
                        {
                            // Get type of script, then get associated icon from utilities
                            string      pathToScript = AssetDatabase.GUIDToAssetPath(a.Value);
                            MonoScript  script       = AssetDatabase.LoadAssetAtPath <MonoScript>(pathToScript);
                            System.Type tData;
                            var         sot = SmartEditorUtils.GetSmartObjectType(script.GetClass(), out tData);

                            //TODO Implement icons for component types
                            if (sot == SmartEditorUtils.SmartObjectType.NONE)
                            {
                                break;
                            }
                            Texture2D icon = SmartEditorUtils.LoadSmartIcon(sot, false, true);

                            // Get guid of icon and jam it in there
                            string pathToIcon = AssetDatabase.GetAssetPath(icon);
                            string iconGuid   = AssetDatabase.AssetPathToGUID(pathToIcon);

                            bool modified = false;
                            if (l.Contains(ICON_DEFAULT))
                            {
                                // Replace entire default icon
                                l        = l.Replace(ICON_DEFAULT, string.Format("{{fileID: 2800000, guid: {0}, type: 3}}", iconGuid));
                                modified = true;
                            }
                            else if (l.Contains(ICON_CUSTOM_HEAD))
                            {
                                // Isolate guid to check if changed
                                string check = l.Trim().Replace(ICON_MATCH, "").Replace(ICON_CUSTOM_HEAD, "").Replace(ICON_CUSTOM_TAIL, "");
                                if (check != iconGuid)
                                {
                                    var sb = new System.Text.StringBuilder();

                                    // Whitespace
                                    for (int j = 0; j < l.Length; ++j)
                                    {
                                        if (l[j] != ' ')
                                        {
                                            break;
                                        }
                                        sb.Append(' ');
                                    }

                                    // Build with new guid
                                    sb.Append(ICON_MATCH);
                                    sb.Append(ICON_CUSTOM_HEAD);
                                    sb.Append(iconGuid);
                                    sb.Append(ICON_CUSTOM_TAIL);
                                    l = sb.ToString();

                                    modified = true;
                                }
                            }

                            if (modified)
                            {
                                Debug.Log("Setting icon for script " + a.Key);
                                // Save and flag for asset database refresh
                                lines[i] = l;
                                File.WriteAllLines(metaPath, lines);
                                refresh = true;
                            }
                            break;
                        }
                    }
                }
                else
                {
                    Debug.LogError("Meta file not found: " + metaPath);
                }
            }
            #endregion

            if (refresh)
            {
                AssetDatabase.Refresh();
            }
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (!isInitialized)
            {
                Initialize(property);
            }

            Event ev = Event.current;

            GUIContent guiContent = EditorGUIUtility.ObjectContent(folderAsset, typeof(DefaultAsset));

            Rect rect          = EditorGUI.PrefixLabel(position, label);
            Rect textFieldRect = rect;

            Rect objectFieldRect = rect;

            objectFieldRect.x      = textFieldRect.xMax - 19f;
            objectFieldRect.y     += 1.0f;
            objectFieldRect.height = objectFieldRect.height - 2;
            objectFieldRect.width  = 18f;

            GUIStyle textFieldStyle = new GUIStyle("TextField")
            {
                imagePosition = folderAsset ? ImagePosition.ImageLeft : ImagePosition.TextOnly
            };

            if (objectFieldRect.Contains(ev.mousePosition) && ev.type == EventType.MouseDown)
            {
                //Object field press.
                string path = EditorUtility.OpenFolderPanel("Select a folder", "Assets", "");

                if (path.Contains(Application.dataPath))
                {
                    path               = "Assets" + path.Substring(Application.dataPath.Length);
                    folderAsset        = AssetDatabase.LoadAssetAtPath(path, typeof(DefaultAsset));
                    guidSP.stringValue = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(folderAsset));
                }
                else
                {
                    GameConsole.LogError(this, "The path must be in the Assets folder");
                }

                ev.Use();
            }

            if (GUI.Button(textFieldRect, guiContent, textFieldStyle) && folderAsset)
            {
                EditorGUIUtility.PingObject(folderAsset);
            }

            if (GUI.Button(objectFieldRect, "", GUI.skin.GetStyle("ObjectFieldButton")))
            {
                //Just for show.
            }

            if (textFieldRect.Contains(ev.mousePosition))
            {
                //Drag and drop support for folders.
                if (ev.type == EventType.DragUpdated)
                {
                    Object reference = DragAndDrop.objectReferences[0];
                    string path      = AssetDatabase.GetAssetPath(reference);
                    DragAndDrop.visualMode = Directory.Exists(path) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;

                    ev.Use();
                }
                else if (ev.type == EventType.DragPerform)
                {
                    Object reference = DragAndDrop.objectReferences[0];
                    string path      = AssetDatabase.GetAssetPath(reference);

                    if (Directory.Exists(path))
                    {
                        folderAsset        = reference;
                        guidSP.stringValue = AssetDatabase.AssetPathToGUID(path);
                    }

                    ev.Use();
                }
            }
        }
        private void GroupLoadPrefabs(SerializedProperty proprety)
        {
            for (int i = 0; i < proprety.arraySize; i++)
            {
                var        itemProp       = proprety.GetArrayElementAtIndex(i);
                GameObject prefab         = null;
                var        prefabProp     = itemProp.FindPropertyRelative("prefab");
                var        assetNameProp  = itemProp.FindPropertyRelative("panelName");
                var        instanceIDProp = itemProp.FindPropertyRelative("instanceID");

                if (instanceIDProp.intValue != 0)
                {
                    continue;
                }

                if (prefabProp == null)
                {
                    var bundleNameProp = itemProp.FindPropertyRelative("bundleName");
                    var guidProp       = itemProp.FindPropertyRelative("guid");
                    var paths          = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(bundleNameProp.stringValue, assetNameProp.stringValue);
                    if (paths.Length > 0)
                    {
                        prefab = AssetDatabase.LoadAssetAtPath <GameObject>(paths[0]);
                        guidProp.stringValue = AssetDatabase.AssetPathToGUID(paths[0]);
                    }
                }
                else
                {
                    prefab = prefabProp.objectReferenceValue as GameObject;
                }

                if (prefab == null)
                {
                    UnityEditor.EditorUtility.DisplayDialog("空对象", "找不到预制体" + assetNameProp.stringValue, "确认");
                }
                else
                {
                    //var rematrixProp = itemProp.FindPropertyRelative("reset");
                    GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                    if (target is PanelGroup)
                    {
                        if (go.GetComponent <Transform>() is RectTransform)
                        {
                            go.transform.SetParent((target as PanelGroup).transform, false);
                        }
                        else
                        {
                            go.transform.SetParent((target as PanelGroup).transform, true);
                        }
                    }
                    else if (target is PanelGroupObj)
                    {
                        if (go.GetComponent <Transform>() is RectTransform)
                        {
                            var canvas = GameObject.FindObjectOfType <Canvas>();
                            go.transform.SetParent(canvas.transform, false);
                        }
                        else
                        {
                            go.transform.SetParent(null);
                        }
                    }

                    //if (rematrixProp.boolValue)
                    //{
                    //    go.transform.position = Vector3.zero;
                    //    go.transform.localRotation = Quaternion.identity;
                    //}

                    instanceIDProp.intValue = go.GetInstanceID();
                }
            }
        }
Exemple #15
0
        internal static List <string> ScanFileForIncludes(string filePath)
        {
            var fileLines  = File.ReadAllLines(filePath);
            var references = new List <string>();

            foreach (var line in fileLines)
            {
                var includeIndex = line.IndexOf("include", StringComparison.Ordinal);
                if (includeIndex == -1)
                {
                    continue;
                }

                var noSharp = line.IndexOf('#', 0, includeIndex) == -1;
                if (noSharp)
                {
                    continue;
                }

                var indexOfFirstQuote = line.IndexOf('"', includeIndex);
                if (indexOfFirstQuote == -1)
                {
                    continue;
                }

                var indexOfLastQuote = line.IndexOf('"', indexOfFirstQuote + 1);
                if (indexOfLastQuote == -1)
                {
                    continue;
                }

                var path = line.Substring(indexOfFirstQuote + 1, indexOfLastQuote - indexOfFirstQuote - 1);
                path = CSPathTools.EnforceSlashes(path);

                string assetPath;

                if (path.StartsWith("Assets/"))
                {
                    assetPath = path;
                }
                else if (path.IndexOf('/') != -1)
                {
                    var folder = System.IO.Path.GetDirectoryName(filePath);
                    if (folder == null)
                    {
                        continue;
                    }

                    var combinedPath = System.IO.Path.Combine(folder, path);
                    var fullPath     = CSPathTools.EnforceSlashes(System.IO.Path.GetFullPath(combinedPath));
                    var assetsIndex  = fullPath.IndexOf("Assets/", StringComparison.Ordinal);
                    if (assetsIndex == -1)
                    {
                        continue;
                    }

                    assetPath = fullPath.Substring(assetsIndex, fullPath.Length - assetsIndex);
                }
                else
                {
                    var folder = System.IO.Path.GetDirectoryName(filePath);
                    if (folder == null)
                    {
                        continue;
                    }

                    assetPath = CSPathTools.EnforceSlashes(System.IO.Path.Combine(folder, path));
                }

                if (!File.Exists(assetPath))
                {
                    continue;
                }

                var guid = AssetDatabase.AssetPathToGUID(assetPath);

                if (references.IndexOf(guid) != -1)
                {
                    continue;
                }
                {
                    references.Add(guid);
                }
            }

            return(references);
        }
Exemple #16
0
    public override void OnInspectorGUI()
    {
        Init();
        if (animLibs == null)
        {
            GUILayout.Label("no libraries found");
            if (GUILayout.Button("Refresh"))
            {
                initialized = false;
                Init();
            }
        }
        else
        {
            tk2dSpriteAnimator sprite = (tk2dSpriteAnimator)target;

            EditorGUIUtility.LookLikeInspector();
            EditorGUI.indentLevel = 1;

            if (sprite.Library == null)
            {
                sprite.Library = animLibs[0].GetAsset <tk2dSpriteAnimation>();
                GUI.changed    = true;
            }

            // Display animation library
            int    selAnimLib   = 0;
            string selectedGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(sprite.Library));
            for (int i = 0; i < animLibs.Length; ++i)
            {
                if (animLibs[i].assetGUID == selectedGUID)
                {
                    selAnimLib = i;
                    break;
                }
            }

            int newAnimLib = EditorGUILayout.Popup("Anim Lib", selAnimLib, animLibNames);
            if (newAnimLib != selAnimLib)
            {
                Undo.RegisterUndo(targetAnimators, "Sprite Anim Lib");
                foreach (tk2dSpriteAnimator animator in targetAnimators)
                {
                    animator.Library       = animLibs[newAnimLib].GetAsset <tk2dSpriteAnimation>();
                    animator.DefaultClipId = 0;

                    if (animator.Library.clips.Length > 0)
                    {
                        if (animator.Sprite != null)
                        {
                            // automatically switch to the first frame of the new clip
                            var f = animator.Library.clips;
                            foreach (var ff in f)
                            {
                                Debug.LogError(ff.name);
                            }
                            animator.Sprite.SetSprite(animator.Library.clips[animator.DefaultClipId].frames[0].spriteCollection,
                                                      animator.Library.clips[animator.DefaultClipId].frames[0].spriteId);
                        }
                    }
                }
            }

            // Everything else
            if (sprite.Library && sprite.Library.clips.Length > 0)
            {
                int clipId = sprite.DefaultClipId;

                // Sanity check clip id
                clipId = Mathf.Clamp(clipId, 0, sprite.Library.clips.Length - 1);
                if (clipId != sprite.DefaultClipId)
                {
                    sprite.DefaultClipId = clipId;
                    GUI.changed          = true;
                }

                List <string> clipNames = new List <string>(sprite.Library.clips.Length);
                List <int>    clipIds   = new List <int>(sprite.Library.clips.Length);

                // fill names (with ids if necessary)
                for (int i = 0; i < sprite.Library.clips.Length; ++i)
                {
                    if (sprite.Library.clips[i].name != null && sprite.Library.clips[i].name.Length > 0)
                    {
                        string name = sprite.Library.clips[i].name;
                        if (tk2dPreferences.inst.showIds)
                        {
                            name += "\t[" + i.ToString() + "]";
                        }
                        clipNames.Add(name);
                        clipIds.Add(i);
                    }
                }

                int newClipId = EditorGUILayout.IntPopup("Clip", sprite.DefaultClipId, clipNames.ToArray(), clipIds.ToArray());
                if (newClipId != sprite.DefaultClipId)
                {
                    Undo.RegisterUndo(targetAnimators, "Sprite Anim Clip");
                    foreach (tk2dSpriteAnimator animator in targetAnimators)
                    {
                        animator.DefaultClipId = newClipId;

                        if (animator.Sprite != null)
                        {
                            // automatically switch to the first frame of the new clip
                            animator.Sprite.SetSprite(animator.Library.clips[animator.DefaultClipId].frames[0].spriteCollection,
                                                      animator.Library.clips[animator.DefaultClipId].frames[0].spriteId);
                        }
                    }
                }
            }

            // Play automatically
            bool newPlayAutomatically = EditorGUILayout.Toggle("Play automatically", sprite.playAutomatically);
            if (newPlayAutomatically != sprite.playAutomatically)
            {
                Undo.RegisterUndo(targetAnimators, "Sprite Anim Play Automatically");
                foreach (tk2dSpriteAnimator animator in targetAnimators)
                {
                    animator.playAutomatically = newPlayAutomatically;
                }
            }

            if (GUI.changed)
            {
                foreach (tk2dSpriteAnimator spr in targetAnimators)
                {
                    EditorUtility.SetDirty(spr);
                }
            }
        }
    }
Exemple #17
0
        // static string[] GatherDependenciesFromSourceFile(string path) {
        //     // Called before actual import for each changed asset that is imported by this importer type
        //     // Extract the dependencies for the asset specified in path.
        //     // For asset dependencies that are discovered, return them in the string array, where the string is the path to asset
        //
        //     // TODO: Texture files with relative URIs should be included here
        //     return null;
        // }

        public override void OnImportAsset(AssetImportContext ctx)
        {
            reportItems = null;

            var downloadProvider = new EditorDownloadProvider();
            var logger           = new CollectingLogger();

            m_Gltf = new GltfImport(
                downloadProvider,
                new UninterruptedDeferAgent(),
                null,
                logger
                );

            if (importSettings == null)
            {
                // Design-time import specific settings
                importSettings = new ImportSettings {
                    // Avoid naming conflicts by default
                    nodeNameMethod = ImportSettings.NameImportMethod.OriginalUnique
                };
            }

            var success = AsyncHelpers.RunSync <bool>(() => m_Gltf.Load(ctx.assetPath, importSettings));

            GameObjectInstantiator instantiator        = null;
            CollectingLogger       instantiationLogger = null;

            if (success)
            {
                m_ImportedNames   = new HashSet <string>();
                m_ImportedObjects = new HashSet <Object>();

                var go = new GameObject("root");
                instantiationLogger = new CollectingLogger();
                instantiator        = new GameObjectInstantiator(m_Gltf, go.transform, instantiationLogger);
                for (var sceneIndex = 0; sceneIndex < m_Gltf.sceneCount; sceneIndex++)
                {
                    success = m_Gltf.InstantiateScene(instantiator, sceneIndex);
                    if (!success)
                    {
                        break;
                    }
                    var sceneTransform = go.transform.GetChild(sceneIndex);
                    var sceneGo        = sceneTransform.gameObject;
                    AddObjectToAsset(ctx, $"scenes/{sceneGo.name}", sceneGo);
                    if (sceneIndex == m_Gltf.defaultSceneIndex)
                    {
                        ctx.SetMainObject(sceneGo);
                    }
                }

                for (var i = 0; i < m_Gltf.textureCount; i++)
                {
                    var texture = m_Gltf.GetTexture(i);
                    if (texture != null)
                    {
                        AddObjectToAsset(ctx, $"textures/{texture.name}", texture);
                    }
                }

                for (var i = 0; i < m_Gltf.materialCount; i++)
                {
                    var mat = m_Gltf.GetMaterial(i);
                    AddObjectToAsset(ctx, $"materials/{mat.name}", mat);
                }

                if (m_Gltf.defaultMaterial != null)
                {
                    // If a default/fallback material was created, import it as well'
                    // to avoid (pink) objects without materials
                    var mat = m_Gltf.defaultMaterial;
                    AddObjectToAsset(ctx, $"materials/{mat.name}", mat);
                }

                var meshes = m_Gltf.GetMeshes();
                if (meshes != null)
                {
                    foreach (var mesh in meshes)
                    {
                        AddObjectToAsset(ctx, $"meshes/{mesh.name}", mesh);
                    }
                }

                var clips = m_Gltf.GetAnimationClips();
                if (clips != null)
                {
                    foreach (var animationClip in clips)
                    {
                        AddObjectToAsset(ctx, $"animations/{animationClip.name}", animationClip);
                    }
                }

                m_ImportedNames   = null;
                m_ImportedObjects = null;
            }

            var deps = new List <GltfAssetDependency>();

            for (var index = 0; index < downloadProvider.assetDependencies.Count; index++)
            {
                var dependency = downloadProvider.assetDependencies[index];
                if (ctx.assetPath == dependency.originalUri)
                {
                    // Skip original gltf/glb file
                    continue;
                }

                var guid = AssetDatabase.AssetPathToGUID(dependency.originalUri);
                if (!string.IsNullOrEmpty(guid))
                {
                    dependency.assetPath = dependency.originalUri;
                    ctx.DependsOnSourceAsset(dependency.assetPath);
                }

                deps.Add(dependency);
            }

            assetDependencies = deps.ToArray();

            var reportItemList = new List <LogItem>();

            reportItemList.AddRange(logger.items);
            if (instantiationLogger?.items != null)
            {
                reportItemList.AddRange(instantiationLogger.items);
            }
            reportItems = reportItemList.ToArray();
        }
Exemple #18
0
        private void GenerateClass()
        {
            VFXConfigEditor config            = target as VFXConfigEditor;
            string          generateAssetPath = string.Format("{0}{1}.cs", config.GeneratePath, VFXConstants.VFC_CONFIG_CLASS_NAME);
            string          generateFullPath  = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("Assets")) + generateAssetPath;

            if (!CheckPath(generateFullPath))
            {
                EditorUtility.DisplayDialog("Generate VFX Config", string.Format("{0}\nPath is invalid", generateFullPath), "ok");
                return;
            }

            if (config.VFXAddressableAssetGroup == null ||
                string.IsNullOrEmpty(config.GeneratePath) ||
                config.ConfigTemplate == null)
            {
                EditorUtility.DisplayDialog("Generate VFX Config", "Config editor has null parameter", "ok");
                return;
            }

            RemoveEmptyOrDuplicateEffects();
            List <ForGenerateVFXConfigItem> vfxConfigItems = new List <ForGenerateVFXConfigItem>();
            HashSet <string>  vfxTypes   = new HashSet <string>();
            List <GameObject> vfxPrefabs = new List <GameObject>();

            for (int iEffect = 0; iEffect < config.Effects.Length; iEffect++)
            {
                GameObject iterEffect = config.Effects[iEffect];
                string     assetPath  = AssetDatabase.GetAssetPath(iterEffect);
                if (string.IsNullOrEmpty(assetPath))
                {
                    Debug.LogError(string.Format("Effect({0}) 不是一个Assets", iEffect), iterEffect);
                    continue;
                }
                string assetName = StringUtility.SubFileNameFromPath(assetPath);
                if (!vfxTypes.Add(assetName))
                {
                    Debug.LogError(string.Format("Effect({0}) FileName({1})重复", iEffect, assetName), iterEffect);
                    continue;
                }

                string assetGuid = AssetDatabase.AssetPathToGUID(assetPath);
                AddressableAssetEntry unitPrefabAssetEntry = AddressableAssetSettingsDefaultObject.Settings.CreateOrMoveEntry(assetGuid, config.VFXAddressableAssetGroup);
                string assetKey = VFXConstants.VFX_EFFECT_ASSET_KEY_STARTWITH + assetName;
                unitPrefabAssetEntry.address = assetKey;
                ForGenerateVFXConfigItem vfxConfigItem = new ForGenerateVFXConfigItem();
                vfxConfigItem.Type       = assetName;
                vfxConfigItem.ItemConfig = new VFXItemConfig(assetKey);
                vfxConfigItems.Add(vfxConfigItem);
                vfxPrefabs.Add(iterEffect);
            }
            VFXConfigForEditorLoader.Get().EffectPrefabs = vfxPrefabs.ToArray();
            VFXConfigForEditorLoader.Save();

            string[]      configTemplateLines = config.ConfigTemplate.text.Split(new char[] { '\n' });
            StringBuilder stringBuilder       = new StringBuilder();

            for (int iLine = 0; iLine < configTemplateLines.Length; iLine++)
            {
                string iterLine = configTemplateLines[iLine].Replace("\r", "");
                if (iterLine.Contains(VFXConstants.VFX_CONFIG_CLASS_NAME_FLAG))
                {
                    stringBuilder.AppendLine(iterLine.Replace(VFXConstants.VFX_CONFIG_CLASS_NAME_FLAG, VFXConstants.VFC_CONFIG_CLASS_NAME));
                }
                else if (iterLine.Contains(VFXConstants.VFX_CONFIG_TYPE_FLAG))
                {
                    stringBuilder.AppendLine(iterLine);
                    for (int iItem = 0; iItem < vfxConfigItems.Count; iItem++)
                    {
                        stringBuilder.AppendLine(string.Format(VFXConstants.VFX_CONFIG_TYPE_FORAMT, vfxConfigItems[iItem].Type));
                    }
                    stringBuilder.AppendLine(string.Format(VFXConstants.VFX_CONFIG_TYPE_FORAMT, "Count"));
                }
                else if (iterLine.Contains(VFXConstants.VFX_CONFIG_ITEM_CONFIGS_FLAG))
                {
                    stringBuilder.AppendLine(iterLine);
                    for (int iItem = 0; iItem < vfxConfigItems.Count; iItem++)
                    {
                        stringBuilder.AppendLine(string.Format(VFXConstants.VFX_CONFIG_ITEM_CONFIG_FORAMT, vfxConfigItems[iItem].ItemConfig.AssetKey));
                    }
                }
                else
                {
                    stringBuilder.AppendLine(iterLine);
                }
            }
            File.WriteAllText(generateFullPath, stringBuilder.ToString());
            AssetDatabase.ImportAsset(generateAssetPath);
            TextAsset generateAsset = AssetDatabase.LoadAssetAtPath(generateAssetPath, typeof(TextAsset)) as TextAsset;

            Selection.activeObject = generateAsset;
        }
Exemple #19
0
        void OnPreprocessTexture()
        {
            if (!s_Initialized)
            {
                return;
            }

            string guid = AssetDatabase.AssetPathToGUID(assetPath);

            if (s_SpriteMeshToTextureCache.ContainsValue(guid))
            {
                TextureImporter    textureImporter        = (TextureImporter)assetImporter;
                SerializedObject   textureImporterSO      = new SerializedObject(textureImporter);
                SerializedProperty textureImporterSprites = textureImporterSO.FindProperty("m_SpriteSheet.m_Sprites");

                foreach (KeyValuePair <string, string> pair in s_SpriteMeshToTextureCache)
                {
                    if (pair.Value == guid)
                    {
                        SpriteMesh     spriteMesh     = LoadSpriteMesh(AssetDatabase.GUIDToAssetPath(pair.Key));
                        SpriteMeshData spriteMeshData = SpriteMeshUtils.LoadSpriteMeshData(spriteMesh);

                        if (spriteMesh && spriteMeshData && spriteMesh.sprite && spriteMeshData.vertices.Length > 0)
                        {
                            if (textureImporter.spriteImportMode == SpriteImportMode.Multiple)
                            {
                                SerializedProperty spriteProp = null;
                                int    i    = 0;
                                string name = "";

                                while (i < textureImporterSprites.arraySize && name != spriteMesh.sprite.name)
                                {
                                    spriteProp = textureImporterSprites.GetArrayElementAtIndex(i);
                                    name       = spriteProp.FindPropertyRelative("m_Name").stringValue;

                                    ++i;
                                }

                                if (name == spriteMesh.sprite.name)
                                {
                                    Rect textureRect = SpriteMeshUtils.CalculateSpriteRect(spriteMesh, 5);
                                    spriteProp.FindPropertyRelative("m_Rect").rectValue     = textureRect;
                                    spriteProp.FindPropertyRelative("m_Alignment").intValue = 9;
                                    spriteProp.FindPropertyRelative("m_Pivot").vector2Value = Vector2.Scale(spriteMeshData.pivotPoint - textureRect.position, new Vector2(1f / textureRect.size.x, 1f / textureRect.size.y));
                                }
                            }
                            else
                            {
                                int width  = 0;
                                int height = 0;
                                SpriteMeshUtils.GetSpriteTextureSize(spriteMesh.sprite, ref width, ref height);
                                textureImporterSO.FindProperty("m_Alignment").intValue       = 9;
                                textureImporterSO.FindProperty("m_SpritePivot").vector2Value = Vector2.Scale(spriteMeshData.pivotPoint, new Vector2(1f / width, 1f / height));
                            }
                        }
                    }
                }

                textureImporterSO.ApplyModifiedProperties();
            }
        }
        /// <summary>
        /// 验证构建结果
        /// </summary>
        private void VerifyingBuildingResult(BuildContext context, AssetBundleManifest unityManifest)
        {
            var buildParameters = context.GetContextObject <AssetBundleBuilder.BuildParametersContext>();
            var buildMapContext = context.GetContextObject <BuildMapContext>();

            string[] buildedBundles = unityManifest.GetAllAssetBundles();

            // 1. 过滤掉原生Bundle
            List <BuildBundleInfo> expectBundles = new List <BuildBundleInfo>(buildedBundles.Length);

            foreach (var bundleInfo in buildMapContext.BundleInfos)
            {
                if (bundleInfo.IsRawFile == false)
                {
                    expectBundles.Add(bundleInfo);
                }
            }

            // 2. 验证数量
            if (buildedBundles.Length != expectBundles.Count)
            {
                Debug.LogWarning($"构建过程中可能存在无效的资源,导致和预期构建的Bundle数量不一致!");
            }

            // 3. 正向验证Bundle
            foreach (var bundleName in buildedBundles)
            {
                if (buildMapContext.IsContainsBundle(bundleName) == false)
                {
                    throw new Exception($"Should never get here !");
                }
            }

            // 4. 反向验证Bundle
            bool isPass = true;

            foreach (var expectBundle in expectBundles)
            {
                bool isMatch = false;
                foreach (var buildedBundle in buildedBundles)
                {
                    if (buildedBundle == expectBundle.BundleName)
                    {
                        isMatch = true;
                        break;
                    }
                }
                if (isMatch == false)
                {
                    isPass = false;
                    Debug.LogWarning($"没有找到预期构建的Bundle文件 : {expectBundle.BundleName}");
                }
            }
            if (isPass == false)
            {
                throw new Exception("构建结果验证没有通过,请参考警告日志!");
            }

            // 5. 验证Asset
            var buildMode = buildParameters.Parameters.BuildMode;

            if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
            {
                int progressValue = 0;
                foreach (var buildedBundle in buildedBundles)
                {
                    string   filePath                = $"{buildParameters.PipelineOutputDirectory}/{buildedBundle}";
                    string[] allBuildinAssetPaths    = GetAssetBundleAllAssets(filePath);
                    string[] expectBuildinAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle);
                    if (expectBuildinAssetPaths.Length != allBuildinAssetPaths.Length)
                    {
                        Debug.LogWarning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}");
                        isPass = false;
                        continue;
                    }

                    foreach (var buildinAssetPath in allBuildinAssetPaths)
                    {
                        var guid = AssetDatabase.AssetPathToGUID(buildinAssetPath);
                        if (string.IsNullOrEmpty(guid))
                        {
                            Debug.LogWarning($"无效的资源路径,请检查路径是否带有特殊符号或中文:{buildinAssetPath}");
                            isPass = false;
                            continue;
                        }

                        bool isMatch = false;
                        foreach (var exceptBuildAssetPath in expectBuildinAssetPaths)
                        {
                            var guidExcept = AssetDatabase.AssetPathToGUID(exceptBuildAssetPath);
                            if (guid == guidExcept)
                            {
                                isMatch = true;
                                break;
                            }
                        }
                        if (isMatch == false)
                        {
                            Debug.LogWarning($"在构建的Bundle文件里发现了没有匹配的资源对象:{buildinAssetPath}");
                            isPass = false;
                            continue;
                        }
                    }

                    EditorTools.DisplayProgressBar("验证构建结果", ++progressValue, buildedBundles.Length);
                }
                EditorTools.ClearProgressBar();
                if (isPass == false)
                {
                    throw new Exception("构建结果验证没有通过,请参考警告日志!");
                }
            }

            // 卸载所有加载的Bundle
            BuildRunner.Log("构建结果验证成功!");
        }
Exemple #21
0
    public override void OnInspectorGUI()
    {
        spriteUiVisible = EditorGUILayout.Foldout(spriteUiVisible, "Sprite");
        if (spriteUiVisible)
        {
            base.OnInspectorGUI();
        }

        Init();
        if (animLibs == null)
        {
            GUILayout.Label("no libraries found");
            if (GUILayout.Button("Refresh"))
            {
                initialized = false;
                Init();
            }
        }
        else
        {
            tk2dAnimatedSprite sprite = (tk2dAnimatedSprite)target;

            EditorGUIUtility.LookLikeInspector();
            EditorGUI.indentLevel = 1;

            if (sprite.anim == null)
            {
                sprite.anim = animLibs[0].GetAsset <tk2dSpriteAnimation>();
                GUI.changed = true;
            }

            // Display animation library
            int    selAnimLib   = 0;
            string selectedGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(sprite.anim));
            for (int i = 0; i < animLibs.Length; ++i)
            {
                if (animLibs[i].assetGUID == selectedGUID)
                {
                    selAnimLib = i;
                    break;
                }
            }

            int newAnimLib = EditorGUILayout.Popup("Anim Lib", selAnimLib, animLibNames);
            if (newAnimLib != selAnimLib)
            {
                sprite.anim   = animLibs[newAnimLib].GetAsset <tk2dSpriteAnimation>();
                sprite.clipId = 0;

                if (sprite.anim.clips.Length > 0)
                {
                    // automatically switch to the first frame of the new clip
                    sprite.SwitchCollectionAndSprite(sprite.anim.clips[sprite.clipId].frames[0].spriteCollection,
                                                     sprite.anim.clips[sprite.clipId].frames[0].spriteId);
                }
            }

            // Everything else
            if (sprite.anim && sprite.anim.clips.Length > 0)
            {
                int clipId = sprite.clipId;

                // Sanity check clip id
                clipId = Mathf.Clamp(clipId, 0, sprite.anim.clips.Length - 1);
                if (clipId != sprite.clipId)
                {
                    sprite.clipId = clipId;
                    GUI.changed   = true;
                }

                string[] clipNames = new string[sprite.anim.clips.Length];
                // fill names (with ids if necessary)
                if (tk2dPreferences.inst.showIds)
                {
                    for (int i = 0; i < sprite.anim.clips.Length; ++i)
                    {
                        if (sprite.anim.clips[i].name != null && sprite.anim.clips[i].name.Length > 0)
                        {
                            clipNames[i] = sprite.anim.clips[i].name + "\t[" + i.ToString() + "]";
                        }
                        else
                        {
                            clipNames[i] = sprite.anim.clips[i].name;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sprite.anim.clips.Length; ++i)
                    {
                        clipNames[i] = sprite.anim.clips[i].name;
                    }
                }

                int newClipId = EditorGUILayout.Popup("Clip", sprite.clipId, clipNames);
                if (newClipId != sprite.clipId)
                {
                    sprite.clipId = newClipId;
                    // automatically switch to the first frame of the new clip
                    sprite.SwitchCollectionAndSprite(sprite.anim.clips[sprite.clipId].frames[0].spriteCollection,
                                                     sprite.anim.clips[sprite.clipId].frames[0].spriteId);
                }
            }

            // Play automatically
            sprite.playAutomatically = EditorGUILayout.Toggle("Play automatically", sprite.playAutomatically);
            bool oldCreateCollider = sprite.createCollider;
            sprite.createCollider = EditorGUILayout.Toggle("Create collider", sprite.createCollider);
            if (oldCreateCollider != sprite.createCollider)
            {
                sprite.EditMode__CreateCollider();
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(sprite);
            }
        }
    }
Exemple #22
0
 public static string pathToGUID(string path)
 {
     return(AssetDatabase.AssetPathToGUID(path));
 }
Exemple #23
0
        private void AssignAssetID(GameObject prefab)
        {
            string assetPath = AssetDatabase.GetAssetPath(prefab);

            this.m_AssetId = NetworkHash128.Parse(AssetDatabase.AssetPathToGUID(assetPath));
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath);

            if (oldShader != null)
            {
                ShaderUtil.ClearShaderMessages(oldShader);
            }

            List <PropertyCollector.TextureInfo> configuredTextures;
            string path = ctx.assetPath;

            AssetCollection assetCollection = new AssetCollection();

            MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);

            var textGraph = File.ReadAllText(path, Encoding.UTF8);
            var graph     = new GraphData
            {
                messageManager = new MessageManager(), assetGuid = AssetDatabase.AssetPathToGUID(path)
            };

            MultiJson.Deserialize(graph, textGraph);
            graph.OnEnable();
            graph.ValidateGraph();

            Shader shader = null;

#if VFX_GRAPH_10_0_0_OR_NEWER
            if (!graph.isOnlyVFXTarget)
#endif
            {
                // build the shader text
                // this will also add Target dependencies into the asset collection
                var text = GetShaderText(path, out configuredTextures, assetCollection, graph);

#if UNITY_2021_1_OR_NEWER
                // 2021.1 or later is guaranteed to have the new version of this function
                shader = ShaderUtil.CreateShaderAsset(ctx, text, false);
#else
                // earlier builds of Unity may or may not have it
                // here we try to invoke the new version via reflection
                var createShaderAssetMethod = typeof(ShaderUtil).GetMethod(
                    "CreateShaderAsset",
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding,
                    null,
                    new Type[] { typeof(AssetImportContext), typeof(string), typeof(bool) },
                    null);

                if (createShaderAssetMethod != null)
                {
                    shader = createShaderAssetMethod.Invoke(null, new Object[] { ctx, text, false }) as Shader;
                }
                else
                {
                    // method doesn't exist in this version of Unity, call old version
                    // this doesn't create dependencies properly, but is the best that we can do
                    shader = ShaderUtil.CreateShaderAsset(text, false);
                }
#endif

                ReportErrors(graph, shader, path);

                EditorMaterialUtility.SetShaderDefaults(
                    shader,
                    configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
                EditorMaterialUtility.SetShaderNonModifiableDefaults(
                    shader,
                    configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
            }

            UnityEngine.Object mainObject = shader;
#if VFX_GRAPH_10_0_0_OR_NEWER
            ShaderGraphVfxAsset vfxAsset = null;
            if (graph.hasVFXTarget)
            {
                vfxAsset = GenerateVfxShaderGraphAsset(graph);
                if (mainObject == null)
                {
                    mainObject = vfxAsset;
                }
                else
                {
                    //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset
                    vfxAsset.name = Path.GetFileNameWithoutExtension(path);
                    ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset);
                }
            }
#endif

            Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon");
            ctx.AddObjectToAsset("MainAsset", mainObject, texture);
            ctx.SetMainObject(mainObject);

            foreach (var target in graph.activeTargets)
            {
                if (target is IHasMetadata iHasMetadata)
                {
                    var metadata = iHasMetadata.GetMetadataObject();
                    if (metadata == null)
                    {
                        continue;
                    }

                    metadata.hideFlags = HideFlags.HideInHierarchy;
                    ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata);
                }
            }

            var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>();
            sgMetadata.hideFlags         = HideFlags.HideInHierarchy;
            sgMetadata.assetDependencies = new List <UnityEngine.Object>();

            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage))
                {
                    // this sucks that we have to fully load these assets just to set the reference,
                    // which then gets serialized as the GUID that we already have here.  :P

                    var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
                    if (!string.IsNullOrEmpty(dependencyPath))
                    {
                        sgMetadata.assetDependencies.Add(
                            AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object)));
                    }
                }
            }

            List <GraphInputData> inputInspectorDataList = new List <GraphInputData>();
            foreach (AbstractShaderProperty property in graph.properties)
            {
                // Don't write out data for non-exposed blackboard items
                if (!property.isExposed)
                {
                    continue;
                }

                // VTs are treated differently
                if (property is VirtualTextureShaderProperty virtualTextureShaderProperty)
                {
                    inputInspectorDataList.Add(MinimalCategoryData.ProcessVirtualTextureProperty(virtualTextureShaderProperty));
                }
                else
                {
                    inputInspectorDataList.Add(new GraphInputData()
                    {
                        referenceName = property.referenceName, propertyType = property.propertyType, isKeyword = false
                    });
                }
            }
            foreach (ShaderKeyword keyword in graph.keywords)
            {
                // Don't write out data for non-exposed blackboard items
                if (!keyword.isExposed)
                {
                    continue;
                }

                var sanitizedReferenceName = keyword.referenceName;
                if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
                {
                    sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
                }

                inputInspectorDataList.Add(new GraphInputData()
                {
                    referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true
                });
            }

            sgMetadata.categoryDatas = new List <MinimalCategoryData>();
            foreach (CategoryData categoryData in graph.categories)
            {
                // Don't write out empty categories
                if (categoryData.childCount == 0)
                {
                    continue;
                }

                MinimalCategoryData mcd = new MinimalCategoryData()
                {
                    categoryName  = categoryData.name,
                    propertyDatas = new List <GraphInputData>()
                };
                foreach (var input in categoryData.Children)
                {
                    GraphInputData propData;
                    // Only write out data for exposed blackboard items
                    if (input.isExposed == false)
                    {
                        continue;
                    }

                    // VTs are treated differently
                    if (input is VirtualTextureShaderProperty virtualTextureShaderProperty)
                    {
                        propData = MinimalCategoryData.ProcessVirtualTextureProperty(virtualTextureShaderProperty);
                        inputInspectorDataList.RemoveAll(inputData => inputData.referenceName == propData.referenceName);
                        mcd.propertyDatas.Add(propData);
                        continue;
                    }
                    else if (input is ShaderKeyword keyword)
                    {
                        var sanitizedReferenceName = keyword.referenceName;
                        if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
                        {
                            sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
                        }

                        propData = new GraphInputData()
                        {
                            referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true
                        };
                    }
                    else
                    {
                        var prop = input as AbstractShaderProperty;
                        propData = new GraphInputData()
                        {
                            referenceName = input.referenceName, propertyType = prop.propertyType, isKeyword = false
                        };
                    }

                    mcd.propertyDatas.Add(propData);
                    inputInspectorDataList.Remove(propData);
                }
                sgMetadata.categoryDatas.Add(mcd);
            }

            // Any uncategorized elements get tossed into an un-named category at the top as a fallback
            if (inputInspectorDataList.Count > 0)
            {
                sgMetadata.categoryDatas.Insert(0, new MinimalCategoryData()
                {
                    categoryName = "", propertyDatas = inputInspectorDataList
                });
            }

            ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata);

            // declare dependencies
            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency))
                {
                    ctx.DependsOnSourceAsset(asset.Key);

                    // I'm not sure if this warning below is actually used or not, keeping it to be safe
                    var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key);

                    // Ensure that dependency path is relative to project
                    if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/"))
                    {
                        Debug.LogWarning($"Invalid dependency path: {assetPath}", mainObject);
                    }
                }

                // NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies
                // HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies
                // on GUIDs that don't exist in the project.  For both of those reasons, we re-declare the dependencies here.
                if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
                {
                    ctx.DependsOnArtifact(asset.Key);
                }
            }
        }
Exemple #25
0
    public override void OnInspectorGUI()
    {
        var registry = ReplicatedEntityRegistry.GetReplicatedEntityRegistry();

        if (registry == null)
        {
            EditorGUILayout.HelpBox("Make sure you have a ReplicatedEntityRegistry in project", MessageType.Error);
            return;
        }

        var replicatedEntity = target as ReplicatedEntity;

        var guid  = "";
        var stage = PrefabStageUtility.GetPrefabStage(replicatedEntity.gameObject);

        if (stage != null)
        {
            guid = AssetDatabase.AssetPathToGUID(stage.prefabAssetPath);
        }
        else
        {
            if (!PrefabUtility.IsAnyPrefabInstanceRoot(replicatedEntity.gameObject) && !Application.isPlaying)
            {
                EditorGUILayout.HelpBox("Replicated entity must be placed on root of prefab", MessageType.Error);
                return;
            }

            var path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(replicatedEntity.gameObject);
            guid = AssetDatabase.AssetPathToGUID(path);
        }

        var registryIndex = registry != null?registry.GetId(guid) : -1;

        GUILayout.Label("Entity registry index:" + replicatedEntity.registryId);

        if (Application.isPlaying)
        {
            return;
        }

        GUILayout.Label("Registry index:" + registryIndex);

        if (registryIndex != replicatedEntity.registryId)
        {
            EditorGUILayout.HelpBox("Local index does not match client registry index", MessageType.Error);
        }

        if (registryIndex != -1 || replicatedEntity.registryId != -1)
        {
            if (GUILayout.Button("Unregister"))
            {
                if (registryIndex != -1)
                {
                    registry.ClearAtId(registryIndex);
                }
                replicatedEntity.registryId = -1;

                PrefabUtility.SaveAsPrefabAsset(replicatedEntity.gameObject, stage.prefabAssetPath);
//                EditorUtility.SetDirty(replicatedEntity);
            }
        }
        else
        {
            EditorGUILayout.HelpBox("NOT REGISTERED!", MessageType.Error);

            if (GUILayout.Button("Register"))
            {
                registryIndex = registry.FindFreeId();


                registry.SetPrefab(registryIndex, guid);

                replicatedEntity.registryId = registryIndex;
                PrefabUtility.SaveAsPrefabAsset(replicatedEntity.gameObject, stage.prefabAssetPath);
//                EditorUtility.SetDirty(replicatedEntity);
            }
        }
    }
 public override void SaveReferences()
 {
     EditorPrefs.SetString(PrefKey, AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(countdownAnimation)));
 }
Exemple #27
0
        public static void SetAddressbaleGroupName()
        {
            try
            {
                var asset           = AssetDatabase.LoadAssetAtPath <AddressableAssetSettings>(SettingPath);
                var addressGroupCfg = AssetDatabase.LoadAssetAtPath <BundleGroups>(BundleGroupConfigPath);
                var groups          = addressGroupCfg.BundleItems;
                EditorUtility.DisplayCancelableProgressBar("Addressable 资源处理中", "清理Groups..", 0.1f);
                for (int i = asset.groups.Count - 1; i >= 0; i--)
                {
                    var assetGroup = asset.groups[i];
                    if (assetGroup == null)
                    {
                        asset.groups.RemoveAt(i);
                        continue;
                    }

                    if (assetGroup.name.Contains("Builde In Data"))
                    {
                        continue;
                    }

                    if (assetGroup.IsDefaultGroup())
                    {
                        continue;
                    }

                    if (assetGroup.entries.Count <= 0 && IsDefaultGroup(assetGroup))
                    {
                        asset.groups.RemoveAt(i);
                        asset.RemoveGroup(assetGroup);
                    }
                }

                EditorUtility.DisplayCancelableProgressBar("Addressable 资源处理中", "清理Groups..", 0.2f);

                for (int j = 0; j < groups.Count; j++)
                {
                    var item = groups[j];

                    if (string.IsNullOrEmpty(item.groupName))
                    {
                        throw new ArgumentNullException("groupName");
                    }
                    EditorUtility.DisplayCancelableProgressBar("Addressable 资源处理中", item.groupName, (float)j / groups.Count);
                    var assets       = item.GetAllAssets();
                    var addressGroup = asset.FindGroup(item.groupName);
                    if (!addressGroup)
                    {
                        var groupSchmeTemple = (asset.GroupTemplateObjects[0] as AddressableAssetGroupTemplate);
                        addressGroup = asset.CreateGroup(item.groupName, false, false, false, null, groupSchmeTemple.GetTypes());
                        groupSchmeTemple.ApplyToAddressableAssetGroup(addressGroup);
                    }

                    if (addressGroup)
                    {
                        var bundleAssetGroup = addressGroup.GetSchema <BundledAssetGroupSchema>();
                        if (!bundleAssetGroup)
                        {
                            bundleAssetGroup = addressGroup.AddSchema <BundledAssetGroupSchema>(false);
                        }

                        bundleAssetGroup.UseAssetBundleCrc = false;
                        bundleAssetGroup.BundleNaming      = item.namingStyle;
                        bundleAssetGroup.BundleMode        = item.bundleMode;


                        var contentUpdateScnema = addressGroup.GetSchema <ContentUpdateGroupSchema>();
                        if (!contentUpdateScnema)
                        {
                            contentUpdateScnema = addressGroup.AddSchema <ContentUpdateGroupSchema>(false);
                        }
                        contentUpdateScnema.StaticContent = true;
                    }
                    foreach (var assetPath in assets)
                    {
                        var guid  = AssetDatabase.AssetPathToGUID(assetPath);
                        var entry = asset.CreateOrMoveEntry(guid, addressGroup, false, false);
                        entry.SetAddress(GetSimpleAddresName(entry.address), false);
                    }
                }

                for (int i = 0; i < asset.groups.Count; i++)
                {
                    var item = asset.groups[i];
                    if (!IsDefaultGroup(item))
                    {
                        foreach (var entry in item.entries.ToArray())
                        {
                            string filePath = Path.Combine(Application.dataPath, "BundleResource", entry.address);
                            if (string.IsNullOrEmpty(entry.AssetPath))
                            {
                                item.RemoveAssetEntry(entry);
                                Debug.Log("AssetRemove:" + filePath);
                            }

                            if (File.Exists(filePath))
                            {
                                entry.SetLabel("dlc-content", false);
                                entry.SetAddress(GetSimpleAddresName(entry.address), false);
                            }
                            else
                            {
                                Debug.Log(filePath);
                                item.RemoveAssetEntry(entry);
                            }
                        }
                    }
                }

                AssetDatabase.SaveAssets();
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }
Exemple #28
0
        public override void OnInspectorGUI()
        {
            GraphData GetGraphData(AssetImporter importer)
            {
                var textGraph   = File.ReadAllText(importer.assetPath, Encoding.UTF8);
                var graphObject = CreateInstance <GraphObject>();

                graphObject.hideFlags = HideFlags.HideAndDontSave;
                bool isSubGraph;
                var  extension = Path.GetExtension(importer.assetPath).Replace(".", "");

                switch (extension)
                {
                case ShaderGraphImporter.Extension:
                    isSubGraph = false;
                    break;

                case ShaderGraphImporter.LegacyExtension:
                    isSubGraph = false;
                    break;

                case ShaderSubGraphImporter.Extension:
                    isSubGraph = true;
                    break;

                default:
                    throw new Exception($"Invalid file extension {extension}");
                }
                var assetGuid = AssetDatabase.AssetPathToGUID(importer.assetPath);

                graphObject.graph = new GraphData
                {
                    assetGuid = assetGuid, isSubGraph = isSubGraph, messageManager = null
                };
                MultiJson.Deserialize(graphObject.graph, textGraph);
                graphObject.graph.OnEnable();
                graphObject.graph.ValidateGraph();
                return(graphObject.graph);
            }

            if (GUILayout.Button("Open Shader Editor"))
            {
                AssetImporter importer = target as AssetImporter;
                Debug.Assert(importer != null, "importer != null");
                ShowGraphEditWindow(importer.assetPath);
            }
            if (GUILayout.Button("View Generated Shader"))
            {
                AssetImporter importer  = target as AssetImporter;
                string        assetName = Path.GetFileNameWithoutExtension(importer.assetPath);
                string        path      = String.Format("Temp/GeneratedFromGraph-{0}.shader", assetName.Replace(" ", ""));

                var graphData = GetGraphData(importer);
                var generator = new Generator(graphData, null, GenerationMode.ForReals, assetName);
                if (GraphUtil.WriteToFile(path, generator.generatedShader))
                {
                    GraphUtil.OpenFile(path);
                }
            }
            if (Unsupported.IsDeveloperMode())
            {
                if (GUILayout.Button("View Preview Shader"))
                {
                    AssetImporter importer  = target as AssetImporter;
                    string        assetName = Path.GetFileNameWithoutExtension(importer.assetPath);
                    string        path      = String.Format("Temp/GeneratedFromGraph-{0}-Preview.shader", assetName.Replace(" ", ""));

                    var graphData = GetGraphData(importer);
                    var generator = new Generator(graphData, null, GenerationMode.Preview, $"{assetName}-Preview");
                    if (GraphUtil.WriteToFile(path, generator.generatedShader))
                    {
                        GraphUtil.OpenFile(path);
                    }
                }
            }
            if (GUILayout.Button("Copy Shader"))
            {
                AssetImporter importer  = target as AssetImporter;
                string        assetName = Path.GetFileNameWithoutExtension(importer.assetPath);

                var graphData = GetGraphData(importer);
                var generator = new Generator(graphData, null, GenerationMode.ForReals, assetName);
                GUIUtility.systemCopyBuffer = generator.generatedShader;
            }

            ApplyRevertGUI();
        }
Exemple #29
0
        public static void LoadPackages()
        {
            if (Application.isPlaying || _loaded)
            {
                return;
            }

#if !(UNITY_5 || UNITY_5_3_OR_NEWER)
            EditorApplication.update -= EditorApplication_Update;
            EditorApplication.update += EditorApplication_Update;
#endif
            _loaded = true;

            UIPackage.RemoveAllPackages();
            FontManager.Clear();
            NTexture.DisposeEmpty();
            UIObjectFactory.Clear();

            string[] ids = AssetDatabase.FindAssets("_fui t:textAsset");
            int      cnt = ids.Length;
            for (int i = 0; i < cnt; i++)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(ids[i]);
                int    pos       = assetPath.LastIndexOf("_fui");
                if (pos == -1)
                {
                    continue;
                }

                assetPath = assetPath.Substring(0, pos);
                if (AssetDatabase.AssetPathToGUID(assetPath) != null)
                {
                    UIPackage.AddPackage(assetPath,
                                         (string name, string extension, System.Type type, out DestroyMethod destroyMethod) =>
                    {
                        destroyMethod = DestroyMethod.Unload;
                        return(AssetDatabase.LoadAssetAtPath(name + extension, type));
                    }
                                         );
                }
            }

            List <UIPackage> pkgs = UIPackage.GetPackages();
            pkgs.Sort(CompareUIPackage);

            cnt = pkgs.Count;
            packagesPopupContents = new GUIContent[cnt + 1];
            for (int i = 0; i < cnt; i++)
            {
                packagesPopupContents[i] = new GUIContent(pkgs[i].name);
            }
            packagesPopupContents[cnt] = new GUIContent("Please Select");

            UIConfig.ClearResourceRefs();
            UIConfig[] configs = GameObject.FindObjectsOfType <UIConfig>();
            foreach (UIConfig config in configs)
            {
                config.Load();
            }

            EMRenderSupport.Reload();
        }
Exemple #30
0
    public void AddSpriteCollectionData(tk2dSpriteCollectionData sc)
    {
#if UNITY_EDITOR
        // prune list
        GetSpriteCollectionIndex();
        spriteCollectionIndex.RemoveAll(item => item == null);
        string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(sc));

        bool existing = false;
        tk2dSpriteCollectionIndex indexEntry = null;
        foreach (var v in spriteCollectionIndex)
        {
            if (v.spriteCollectionDataGUID == guid)
            {
                indexEntry = v;
                existing   = true;
                break;
            }
        }
        if (indexEntry == null)
        {
            indexEntry = new tk2dSpriteCollectionIndex();
        }

        indexEntry.name = sc.spriteCollectionName;
        indexEntry.spriteCollectionDataGUID = guid;
        indexEntry.spriteCollectionGUID     = sc.spriteCollectionGUID;
        indexEntry.spriteNames             = new string[sc.spriteDefinitions.Length];
        indexEntry.spriteTextureGUIDs      = new string[sc.spriteDefinitions.Length];
        indexEntry.spriteTextureTimeStamps = new string[sc.spriteDefinitions.Length];
        indexEntry.version = sc.version;
        indexEntry.managedSpriteCollection = sc.managedSpriteCollection;
        indexEntry.loadable  = sc.loadable;
        indexEntry.assetName = sc.assetName;
        for (int i = 0; i < sc.spriteDefinitions.Length; ++i)
        {
            var s = sc.spriteDefinitions[i];
            if (s != null)
            {
                indexEntry.spriteNames[i]        = sc.spriteDefinitions[i].name;
                indexEntry.spriteTextureGUIDs[i] = sc.spriteDefinitions[i].sourceTextureGUID;
                string assetPath = AssetDatabase.GUIDToAssetPath(indexEntry.spriteTextureGUIDs[i]);
                if (assetPath.Length > 0 && System.IO.File.Exists(assetPath))
                {
                    indexEntry.spriteTextureTimeStamps[i] = (System.IO.File.GetLastWriteTime(assetPath) - new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds.ToString();
                }
                else
                {
                    indexEntry.spriteTextureTimeStamps[i] = "0";
                }
            }
            else
            {
                indexEntry.spriteNames[i]             = "";
                indexEntry.spriteTextureGUIDs[i]      = "";
                indexEntry.spriteTextureTimeStamps[i] = "";
            }
        }

        if (!existing)
        {
            spriteCollectionIndex.Add(indexEntry);
        }
#endif
    }