コード例 #1
0
        private void OnGUI()
        {
            if (!CheckForRequirements())
            {
                return;
            }
            EditorGUILayout.BeginHorizontal();
            painting = GUILayout.Toggle(painting, "painting", "Button");
            EditorGUILayout.LabelField(new GUIContent(layerIndex + ":" + paletteIndex), GUILayout.Width(30));
            EditorGUILayout.EndHorizontal();
            brushRotation = EditorGUILayout.Vector3Field("Brush Direction", brushRotation);
            //if (painting)
            {
                //if (layerIndex < -1 || layerIndex >= t.tileSet.layers.Count) return;
                layerIndex   = Mathf.Clamp(layerIndex, -1, t.tileSet.layers.Count - 1);
                paletteIndex = Mathf.Clamp(paletteIndex, 0,
                                           layerIndex == -1 ? (t.tileSet.tiles.Count - 1) : (t.tileSet.layers[layerIndex].layerObjects.Count - 1));
                paletteIndex = Mathf.Max(0, paletteIndex);
                if (layerIndex == -1)
                {
                    selectedTileGuid = t.tileSet.tiles[paletteIndex].guid;
                }
                else if (t.tileSet.layers[layerIndex]?.layerObjects.Count > 0)
                {
                    selectedTileGuid = t.tileSet.layers[layerIndex]?.layerObjects[paletteIndex]?.guid;
                }
                if (!string.IsNullOrEmpty(selectedTileGuid))
                {
                    t.tileSet.TileFromGuid.TryGetValue(selectedTileGuid, out selectedTile);
                }
                if (!selectedTile)
                {
                    selectedTile     = t.tileSet.tiles[0];
                    selectedTileGuid = selectedTile.guid;
                }
            }
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Grid Visibility ");
            rasterVisibility = (RasterVisibility)EditorGUILayout.EnumPopup(rasterVisibility);
            rasterColor      = EditorGUILayout.ColorField(rasterColor);
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.BeginHorizontal();
            targetHeigth = EditorGUILayout.IntField("Heigth: ", targetHeigth);
            // activeLayer = EditorGUILayout.IntField("Layer:", activeLayer);
            EditorGUILayout.EndHorizontal();
            Event e = Event.current;

            if (e.type == EventType.DragUpdated || e.type == EventType.DragPerform)
            {
                Rect myRect = GUILayoutUtility.GetRect(100, 40, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
                GUI.Box(myRect, "Drag and Drop Prefabs to this Box!");
                if (myRect.Contains(e.mousePosition))
                {
                    if (e.type == EventType.DragUpdated)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Move;
                    }
                    if (e.type == EventType.DragPerform)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                        //Debug.Log(DragAndDrop.objectReferences.Length);
                        for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
                        {
                            var draggedTile = DragAndDrop.objectReferences[i] as TileObject;
                            if (!draggedTile)
                            {
                                var draggedGameObject = DragAndDrop.objectReferences[i] as GameObject;
                                draggedTile = TileObject.CreateNewTileFileFromPrefabs(false, draggedGameObject);
                                AssetDatabase.AddObjectToAsset(draggedTile, t.tileSet);
                            }
                            t.tileSet.tiles.Add(draggedTile);
                            if (layerIndex != -1)
                            {
                                t.tileSet.layers[layerIndex].layerObjects.Add(draggedTile);
                            }
                        }
                        t.tileSet.GetDictionaryFromList();
                        DragAndDrop.AcceptDrag();
                        e.Use();
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(t.tileSet));
                    }
                }
            }
            DrawPalette(t.tileSet, Event.current);
            if (GUILayout.Button("Select Atlas"))
            {
                Selection.activeObject = t.tileSet;
            }
            if (GUILayout.Button("Clear Level"))
            {
                t.ClearLevel();
            }
        }
コード例 #2
0
        static void UpdateCacheBank(EditorBankRef bankRef)
        {
            // Clear out any cached events from this bank
            eventCache.EditorEvents.ForEach((x) => x.Banks.Remove(bankRef));

            FMOD.Studio.Bank bank;
            bankRef.LoadResult = EditorUtils.System.loadBankFile(bankRef.Path, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out bank);

            if (bankRef.LoadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED)
            {
                EditorUtils.System.getBank(bankRef.Name, out bank);
                bank.unload();
                bankRef.LoadResult = EditorUtils.System.loadBankFile(bankRef.Path, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out bank);
            }

            if (bankRef.LoadResult == FMOD.RESULT.OK)
            {
                // Iterate all events in the bank and cache them
                FMOD.Studio.EventDescription[] eventList;
                var result = bank.getEventList(out eventList);
                if (result == FMOD.RESULT.OK)
                {
                    foreach (var eventDesc in eventList)
                    {
                        string path;
                        result = eventDesc.getPath(out path);
                        EditorEventRef eventRef = eventCache.EditorEvents.Find((x) => x.Path == path);
                        if (eventRef == null)
                        {
                            eventRef = ScriptableObject.CreateInstance <EditorEventRef>();
                            AssetDatabase.AddObjectToAsset(eventRef, eventCache);
                            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(eventRef));
                            eventRef.Banks = new List <EditorBankRef>();
                            eventCache.EditorEvents.Add(eventRef);
                            eventRef.Parameters = new List <EditorParamRef>();
                        }

                        eventRef.Banks.Add(bankRef);
                        Guid guid;
                        eventDesc.getID(out guid);
                        eventRef.Guid = guid;
                        eventRef.Path = eventRef.name = path;
                        eventDesc.is3D(out eventRef.Is3D);
                        eventDesc.isOneshot(out eventRef.IsOneShot);
                        eventDesc.isStream(out eventRef.IsStream);
                        eventDesc.getMaximumDistance(out eventRef.MaxDistance);
                        eventDesc.getMinimumDistance(out eventRef.MinDistance);
                        eventDesc.getLength(out eventRef.Length);
                        int paramCount = 0;
                        eventDesc.getParameterDescriptionCount(out paramCount);
                        eventRef.Parameters.ForEach((x) => x.Exists = false);
                        for (int paramIndex = 0; paramIndex < paramCount; paramIndex++)
                        {
                            FMOD.Studio.PARAMETER_DESCRIPTION param;
                            eventDesc.getParameterDescriptionByIndex(paramIndex, out param);
                            if ((param.flags & FMOD.Studio.PARAMETER_FLAGS.READONLY) != 0)
                            {
                                continue;
                            }
                            EditorParamRef paramRef = eventRef.Parameters.Find((x) => x.name == param.name);
                            if (paramRef == null)
                            {
                                paramRef = ScriptableObject.CreateInstance <EditorParamRef>();
                                AssetDatabase.AddObjectToAsset(paramRef, eventCache);
                                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(paramRef));
                                eventRef.Parameters.Add(paramRef);
                            }
                            paramRef.Name    = param.name;
                            paramRef.name    = "parameter:/" + Path.GetFileName(path) + "/" + paramRef.Name;
                            paramRef.Min     = param.minimum;
                            paramRef.Max     = param.maximum;
                            paramRef.Default = param.defaultvalue;
                            paramRef.Exists  = true;
                        }
                        eventRef.Parameters.RemoveAll((x) => !x.Exists);
                    }
                }

                // Update global parameter list for each bank
                FMOD.Studio.PARAMETER_DESCRIPTION[] parameterDescriptions;
                result = EditorUtils.System.getParameterDescriptionList(out parameterDescriptions);
                if (result == FMOD.RESULT.OK)
                {
                    for (int i = 0; i < parameterDescriptions.Length; i++)
                    {
                        FMOD.Studio.PARAMETER_DESCRIPTION param = parameterDescriptions[i];
                        if (param.flags == FMOD.Studio.PARAMETER_FLAGS.GLOBAL)
                        {
                            EditorParamRef paramRef = eventCache.EditorParameters.Find((x) =>
                                                                                       (parameterDescriptions[i].id.data1 == x.ID.data1 && param.id.data2 == x.ID.data2));
                            if (paramRef == null)
                            {
                                paramRef = ScriptableObject.CreateInstance <EditorParamRef>();
                                AssetDatabase.AddObjectToAsset(paramRef, eventCache);
                                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(paramRef));
                                eventCache.EditorParameters.Add(paramRef);
                                paramRef.ID = param.id;
                            }
                            paramRef.Name    = paramRef.name = param.name;
                            paramRef.Min     = param.minimum;
                            paramRef.Max     = param.maximum;
                            paramRef.Default = param.defaultvalue;
                            paramRef.Exists  = true;
                        }
                    }
                }
                bank.unload();
            }
            else
            {
                Debug.LogError(string.Format("FMOD Studio: Unable to load {0}: {1}", bankRef.Name, FMOD.Error.String(bankRef.LoadResult)));
                eventCache.StringsBankWriteTime = DateTime.MinValue;
            }
        }
コード例 #3
0
 internal static void GenerateSerializeSubObject(UnityEngine.Object obj, UnityEngine.Object mainAsset)
 {
     obj.hideFlags = HideFlags.HideInHierarchy;
     AssetDatabase.AddObjectToAsset(obj, mainAsset);
     AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(mainAsset));
 }
コード例 #4
0
    private static void SaveNewAsset(Lightbeam lightBeam, bool duplicateMaterial)
    {
        MeshRenderer meshRenderer = (MeshRenderer)lightBeam.GetComponent(typeof(MeshRenderer));

        if (meshRenderer == null)
        {
            meshRenderer = lightBeam.gameObject.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
        }

        MeshFilter meshFilter = (MeshFilter)lightBeam.GetComponent(typeof(MeshFilter));

        if (meshFilter == null)
        {
            meshFilter = lightBeam.gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
        }

        Mesh mesh = meshFilter.sharedMesh;

        if (mesh == null)
        {
            mesh = new Mesh();
        }

        LightbeamSettings settings = GetLigthbeamSettings(lightBeam);

        if (settings != null)
        {
            lightBeam.Settings = ScriptableObject.Instantiate(settings) as LightbeamSettings;
        }
        else
        {
            lightBeam.Settings = ScriptableObject.CreateInstance <LightbeamSettings>();
        }

        lightBeam.Settings.hideFlags = HideFlags.HideInHierarchy;

        Material material       = null;
        Material sourceMaterial = null;

        if (meshRenderer.sharedMaterial != null)
        {
            if (duplicateMaterial)
            {
                material = new Material(meshRenderer.sharedMaterial);
            }
            else
            {
                material = meshRenderer.sharedMaterial;
            }
            sourceMaterial = meshRenderer.sharedMaterial;
        }

        // The default material can be set on the script file from the inspector, this is the preferred way of doing it since you can choose what material to use as default.
        if (material == null && lightBeam.DefaultMaterial != null)
        {
            material = new Material(lightBeam.DefaultMaterial);
        }

        // If the default material wasn't set, try to find the material from the script path.
        if (material == null)
        {
            // Get the light beam folder by getting the path to the script and using that path to find the material.
            MonoScript script     = MonoScript.FromMonoBehaviour(lightBeam);
            string     scriptPath = AssetDatabase.GetAssetPath(script);

            scriptPath = Path.GetDirectoryName(scriptPath);
            string[] directories = scriptPath.Split('/');
            scriptPath = string.Join("/", directories, 0, directories.Length - 1);

            string   materialPath = scriptPath + "/Source/Lightbeam.mat";
            Material mat          = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
            if (mat != null)
            {
                material = new Material(mat);
            }
        }

        // If the material still is null we'll create a new material and assign the shader to it.
        if (material == null)
        {
            material = new Material(Shader.Find("Lightbeam/Lightbeam"));
        }

        meshRenderer.sharedMaterial = material;

        // Copy mesh
        Mesh newMesh = new Mesh();

        newMesh.Clear();
        newMesh.vertices  = mesh.vertices;
        newMesh.triangles = mesh.triangles;
        newMesh.normals   = mesh.vertices;
        newMesh.uv        = mesh.uv;
        newMesh.tangents  = mesh.tangents;
        newMesh.colors    = mesh.colors;

        // Save the mesh asset
        // Find a free name to use
        string savePath  = "";
        string assetPath = AssetDatabase.GetAssetPath(meshFilter.sharedMesh);

        if (assetPath == "")
        {
            assetPath = "Assets/lightbeam";
        }
        else
        {
            assetPath = Path.GetDirectoryName(assetPath) + "/" + Path.GetFileNameWithoutExtension(assetPath);
        }

        int i = 0;

        while (true)
        {
            savePath = assetPath + "_" + i + ".asset";
            if (File.Exists(savePath) == false)
            {
                break;
            }
            i++;
        }
        AssetDatabase.CreateAsset(newMesh, savePath);
        AssetDatabase.AddObjectToAsset(lightBeam.Settings, newMesh);
        AssetDatabase.ImportAsset(savePath);

        // Save the material
        string materialAssetPath = AssetDatabase.GetAssetPath(sourceMaterial);

        if (materialAssetPath == "" || duplicateMaterial)
        {
            if (materialAssetPath == "")
            {
                materialAssetPath = "Assets/lightbeam";
            }
            else
            {
                materialAssetPath = Path.GetDirectoryName(materialAssetPath) + "/" + Path.GetFileNameWithoutExtension(materialAssetPath);
            }

            savePath = "";
            i        = 0;
            while (true)
            {
                savePath = materialAssetPath + "_" + i + ".mat";
                if (File.Exists(savePath) == false)
                {
                    break;
                }
                i++;
            }
            AssetDatabase.CreateAsset(material, savePath);
        }

        meshFilter.sharedMesh       = newMesh;
        meshRenderer.sharedMaterial = material;
    }
コード例 #5
0
        static void UpdateCacheBank(EditorBankRef bankRef)
        {
            // Clear out any cached events from this bank
            eventCache.EditorEvents.ForEach((x) => x.Banks.Remove(bankRef));

            FMOD.Studio.Bank bank;
            bankRef.LoadResult = EditorUtils.System.loadBankFile(bankRef.Path, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out bank);

            if (bankRef.LoadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED)
            {
                EditorUtils.System.getBank(bankRef.Name, out bank);
                bank.unload();
                bankRef.LoadResult = EditorUtils.System.loadBankFile(bankRef.Path, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out bank);
            }

            if (bankRef.LoadResult == FMOD.RESULT.OK)
            {
                // Iterate all events in the bank and cache them
                FMOD.Studio.EventDescription[] eventList;
                var result = bank.getEventList(out eventList);
                if (result == FMOD.RESULT.OK)
                {
                    foreach (var eventDesc in eventList)
                    {
                        string path;
                        eventDesc.getPath(out path);
                        EditorEventRef eventRef = eventCache.EditorEvents.Find((x) => x.Path == path);
                        if (eventRef == null)
                        {
                            eventRef = ScriptableObject.CreateInstance <EditorEventRef>();
                            AssetDatabase.AddObjectToAsset(eventRef, eventCache);
                            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(eventRef));
                            eventRef.Banks = new List <EditorBankRef>();
                            eventCache.EditorEvents.Add(eventRef);
                        }

                        eventRef.Banks.Add(bankRef);
                        Guid guid;
                        eventDesc.getID(out guid);
                        eventRef.Guid = guid;
                        eventRef.Path = path;
                        eventDesc.is3D(out eventRef.Is3D);
                        eventDesc.isOneshot(out eventRef.IsOneShot);
                        eventDesc.isStream(out eventRef.IsStream);
                        eventDesc.getMaximumDistance(out eventRef.MaxDistance);
                        eventDesc.getMinimumDistance(out eventRef.MinDistance);
                        eventDesc.getLength(out eventRef.Length);
                        int paramCount = 0;
                        eventDesc.getParameterCount(out paramCount);
                        eventRef.Parameters = new List <EditorParamRef>(paramCount);
                        for (int paramIndex = 0; paramIndex < paramCount; paramIndex++)
                        {
                            FMOD.Studio.PARAMETER_DESCRIPTION param;
                            eventDesc.getParameterByIndex(paramIndex, out param);
                            if (param.type != FMOD.Studio.PARAMETER_TYPE.GAME_CONTROLLED)
                            {
                                continue;
                            }
                            EditorParamRef paramRef = ScriptableObject.CreateInstance <EditorParamRef>();
                            AssetDatabase.AddObjectToAsset(paramRef, eventCache);
                            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(paramRef));
                            paramRef.Name    = param.name;
                            paramRef.Min     = param.minimum;
                            paramRef.Max     = param.maximum;
                            paramRef.Default = param.defaultvalue;
                            eventRef.Parameters.Add(paramRef);
                        }
                    }
                }

                bank.unload();
            }
            else
            {
                Debug.LogError(String.Format("FMOD Studio: Unable to load {0}: {1}", bankRef.Name, FMOD.Error.String(bankRef.LoadResult)));
                eventCache.StringsBankWriteTime = DateTime.MinValue;
            }
        }
コード例 #6
0
    void OnGUI()
    {
        EditorGUILayout.LabelField("target clip");
        controller = EditorGUILayout.ObjectField(controller, typeof(AnimatorController), false) as AnimatorController;

        if (controller == null)
        {
            return;
        }

        List <AnimationClip> clipList = new List <AnimationClip>();

        var allAsset = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(controller));

        foreach (var asset in allAsset)
        {
            if (asset is AnimationClip)
            {
                var removeClip = asset as AnimationClip;
                if (!clipList.Contains(removeClip))
                {
                    clipList.Add(removeClip);
                }
            }
        }

        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Add new clip");
        EditorGUILayout.BeginVertical("box");
        clipName = EditorGUILayout.TextField(clipName);
        if (clipList.Exists(item => item.name == clipName) || string.IsNullOrEmpty(clipName))
        {
            EditorGUILayout.LabelField("can't create duplicate names or empty");
        }
        else
        {
            if (GUILayout.Button("create"))
            {
                AnimationClip animationClip = AnimatorController.AllocateAnimatorClip(clipName);
                AssetDatabase.AddObjectToAsset(animationClip, controller);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller));
                AssetDatabase.Refresh();
            }
        }
        EditorGUILayout.EndVertical();


        if (clipList.Count == 0)
        {
            return;
        }

        EditorGUILayout.Space();

        EditorGUILayout.LabelField("remove clip");
        EditorGUILayout.BeginVertical("box");

        foreach (var removeClip in clipList)
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(removeClip.name);
            if (GUILayout.Button("remove", GUILayout.Width(100)))
            {
                Object.DestroyImmediate(removeClip, true);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller));
            }
            EditorGUILayout.EndHorizontal();
        }
        EditorGUILayout.EndVertical();
    }
コード例 #7
0
    Load(string srcPath)
    {
        _database = SsAssetPostProcessor.GetDatabase();
        string path = Path.GetDirectoryName(srcPath);

        // new path name of ss anime asset
        string newPath = path + "/assets/" + Path.GetFileNameWithoutExtension(srcPath) + "_ssa.asset";

        // identify the encoding which is Shift-JIS or UTF-8
        Encoding encode = SsEncoding.SJIS;
        {
            StreamReader sr            = File.OpenText(srcPath);
            string       xmlHeaderText = sr.ReadLine();
            // XmlDocument requires one node at least and also needs to get "encoding" attribute.
            string dummy = System.String.Copy(xmlHeaderText);
            dummy          = dummy.Replace("<?xml", "<Dummy");
            dummy          = dummy.Replace("?>", "/>");
            xmlHeaderText += dummy;
            sr.Close();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlHeaderText);
            XmlNode node   = doc.FirstChild.NextSibling;
            string  encStr = node.Attributes["encoding"].Value;
            if (encStr == "shift_jis")
            {
                encode = SsEncoding.SJIS;
            }
            else if (encStr == "utf-8")
            {
                encode = SsEncoding.UTF8;
            }
        }

        // to read SJIS encoded text correctly.
        string textAll = File.ReadAllText(srcPath, encode);

        // create directory if it doesn't exist.
        bool newAsset = false;

        if (!Directory.Exists(path + "/assets"))
        {
            AssetDatabase.CreateFolder(path, "assets");
        }
        else
        {
            // try to open existing asset
            _anmRes = AssetDatabase.LoadAssetAtPath(newPath, typeof(SsAnimation)) as SsAnimation;
        }

        if (_anmRes == null)
        {
            // create new asset
            _anmRes  = ScriptableObject.CreateInstance <SsAnimation>();
            newAsset = true;
        }
        else
        {
            // update existing asset
            ClearPreviousMaterials();
            _anmRes.ImageList = null;
            _anmRes.PartList  = null;
            System.GC.Collect();
        }

        // update imported time
        _anmRes.UpdateImportedTime();

        // save original resource path
        _anmRes.OriginalPath = srcPath;

        // save scale factor at this import.
        if (!_anmRes.UseScaleFactor)
        {
            _anmRes.ScaleFactor = _database.ScaleFactor;
        }

#if _BUILD_UNIFIED_SHADERS
        if (_anmRes._UseUnifiedShader == UseUnifiedShaderEnum.Default)
        {
            // use global setting
            _anmRes.UseUnifiedShader = _database.UseUnifiedShader;
        }
        else
        {
            // use own setting
            _anmRes.UseUnifiedShader = (_anmRes._UseUnifiedShader == UseUnifiedShaderEnum.Yes);
        }
#endif

        if (!LoadXml(path, textAll))
        {
            Debug.LogError("Failed to import animation data: " + srcPath);
            return(false);
        }

        if (newAsset)
        {
            AssetDatabase.CreateAsset(_anmRes, newPath);
        }
        else
        {
            // modification done internally is not applied actual file, so must make it dirty before.
            EditorUtility.SetDirty(_anmRes);
            AssetDatabase.SaveAssets();                 //same as EditorApplication.SaveAssets();
        }

#if false
        // AddObjectToAsset() a_mat.mat -> hoge.ssax.asset
        // ↓
        // hoge.ssax.mat
        //   hoge.ssax.asset
        // umm...
        foreach (var e in _anmRes.ImageList)
        {
            if (e.material != null)
            {
                e.material.name = e.texture.name + "_Mat";
                AssetDatabase.AddObjectToAsset(e.material, _anmRes);

                // Reimport the asset after adding an object.
                // Otherwise the change only shows up when saving the project
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(e.material));
            }
        }
#endif
        return(true);
    }
コード例 #8
0
        private void Finish()
        {
            if (!references)
            {
                GetReferences();
            }

            if (!references)
            {
                return;
            }

            string managerPath = gameName + "/Managers";

            try
            {
                System.IO.Directory.CreateDirectory(Application.dataPath + "/" + managerPath);
            }
            catch (System.Exception e)
            {
                ACDebug.LogError("Wizard aborted - Could not create directory: " + Application.dataPath + "/" + managerPath + ". Please make sure the Assets direcrory is writeable, and that the intended game name contains no special characters.");
                Debug.LogException(e, this);
                pageNumber--;
                return;
            }

            try
            {
                ScriptableObject t = CustomAssetUtility.CreateAsset <SceneManager> ("SceneManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/SceneManager.asset", gameName + "_SceneManager");
                references.sceneManager = (SceneManager)t;

                t = CustomAssetUtility.CreateAsset <SettingsManager> ("SettingsManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/SettingsManager.asset", gameName + "_SettingsManager");
                references.settingsManager = (SettingsManager)t;

                references.settingsManager.saveFileName      = gameName;
                references.settingsManager.cameraPerspective = cameraPerspective;
                references.settingsManager.movingTurning     = movingTurning;
                references.settingsManager.movementMethod    = movementMethod;
                references.settingsManager.inputMethod       = inputMethod;
                references.settingsManager.interactionMethod = interactionMethod;
                references.settingsManager.hotspotDetection  = hotspotDetection;
                if (cameraPerspective == CameraPerspective.TwoPointFiveD)
                {
                    references.settingsManager.forceAspectRatio = true;
                }

                t = CustomAssetUtility.CreateAsset <ActionsManager> ("ActionsManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/ActionsManager.asset", gameName + "_ActionsManager");
                references.actionsManager = (ActionsManager)t;
                AdventureCreator.RefreshActions();
                ActionsManager defaultActionsManager = AssetDatabase.LoadAssetAtPath(Resource.MainFolderPath + "/Default/Default_ActionsManager.asset", typeof(ActionsManager)) as ActionsManager;
                if (defaultActionsManager != null)
                {
                    references.actionsManager.defaultClass     = defaultActionsManager.defaultClass;
                    references.actionsManager.defaultClassName = defaultActionsManager.defaultClassName;
                }

                t = CustomAssetUtility.CreateAsset <VariablesManager> ("VariablesManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/VariablesManager.asset", gameName + "_VariablesManager");
                references.variablesManager = (VariablesManager)t;

                t = CustomAssetUtility.CreateAsset <InventoryManager> ("InventoryManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/InventoryManager.asset", gameName + "_InventoryManager");
                references.inventoryManager = (InventoryManager)t;

                t = CustomAssetUtility.CreateAsset <SpeechManager> ("SpeechManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/SpeechManager.asset", gameName + "_SpeechManager");
                references.speechManager = (SpeechManager)t;

                references.speechManager.ClearLanguages();

                t = CustomAssetUtility.CreateAsset <CursorManager> ("CursorManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/CursorManager.asset", gameName + "_CursorManager");
                references.cursorManager = (CursorManager)t;

                t = CustomAssetUtility.CreateAsset <MenuManager> ("MenuManager", managerPath);
                AssetDatabase.RenameAsset("Assets/" + managerPath + "/MenuManager.asset", gameName + "_MenuManager");
                references.menuManager = (MenuManager)t;

                CursorManager defaultCursorManager = AssetDatabase.LoadAssetAtPath(Resource.MainFolderPath + "/Default/Default_CursorManager.asset", typeof(CursorManager)) as CursorManager;
                if (wizardMenu == WizardMenu.Blank)
                {
                    if (defaultCursorManager != null)
                    {
                        CursorIcon useIcon = new CursorIcon();
                        useIcon.Copy(defaultCursorManager.cursorIcons[0]);
                        references.cursorManager.cursorIcons.Add(useIcon);
                        EditorUtility.SetDirty(references.cursorManager);
                    }
                }
                else
                {
                    if (defaultCursorManager != null)
                    {
                        foreach (CursorIcon defaultIcon in defaultCursorManager.cursorIcons)
                        {
                            CursorIcon newIcon = new CursorIcon();
                            newIcon.Copy(defaultIcon);
                            references.cursorManager.cursorIcons.Add(newIcon);
                        }

                        CursorIconBase pointerIcon = new CursorIconBase();
                        pointerIcon.Copy(defaultCursorManager.pointerIcon);
                        references.cursorManager.pointerIcon = pointerIcon;
                    }
                    else
                    {
                        ACDebug.LogWarning("Cannot find Default_CursorManager asset to copy from!");
                    }
                    references.cursorManager.allowMainCursor = true;
                    EditorUtility.SetDirty(references.cursorManager);

                    MenuManager defaultMenuManager = AssetDatabase.LoadAssetAtPath(Resource.MainFolderPath + "/Default/Default_MenuManager.asset", typeof(MenuManager)) as MenuManager;
                    if (defaultMenuManager != null)
                    {
                                                #if UNITY_EDITOR
                        references.menuManager.drawOutlines = defaultMenuManager.drawOutlines;
                        references.menuManager.drawInEditor = defaultMenuManager.drawInEditor;
                                                #endif
                        references.menuManager.pauseTexture = defaultMenuManager.pauseTexture;

                        if (wizardMenu != WizardMenu.Blank)
                        {
                            System.IO.Directory.CreateDirectory(Application.dataPath + "/" + gameName + "/UI");
                        }
                        foreach (Menu defaultMenu in defaultMenuManager.menus)
                        {
                            Menu newMenu = ScriptableObject.CreateInstance <Menu>();
                            newMenu.Copy(defaultMenu, true, true);
                            newMenu.Recalculate();

                            if (wizardMenu == WizardMenu.DefaultAC)
                            {
                                newMenu.menuSource = MenuSource.AdventureCreator;
                            }
                            else if (wizardMenu == WizardMenu.DefaultUnityUI)
                            {
                                newMenu.menuSource = MenuSource.UnityUiPrefab;
                            }

                            if (defaultMenu.canvas)
                            {
                                string newCanvasPath = "Assets/" + gameName + "/UI/" + defaultMenu.canvas.name + ".prefab";

                                GameObject canvasObInScene = (GameObject)PrefabUtility.InstantiatePrefab(defaultMenu.canvas.gameObject);
                                PrefabUtility.DisconnectPrefabInstance(canvasObInScene);
                                GameObject canvasObNewPrefab = PrefabUtility.CreatePrefab(newCanvasPath, canvasObInScene);

                                newMenu.canvas = canvasObNewPrefab.GetComponent <Canvas>();
                                DestroyImmediate(canvasObInScene);

                                newMenu.rectTransform = null;
                            }

                            foreach (MenuElement newElement in newMenu.elements)
                            {
                                AssetDatabase.AddObjectToAsset(newElement, references.menuManager);
                                newElement.hideFlags = HideFlags.HideInHierarchy;
                            }
                            AssetDatabase.AddObjectToAsset(newMenu, references.menuManager);
                            newMenu.hideFlags = HideFlags.HideInHierarchy;

                            references.menuManager.menus.Add(newMenu);
                        }

                        EditorUtility.SetDirty(references.menuManager);
                    }
                    else
                    {
                        ACDebug.LogWarning("Cannot find Default_MenuManager asset to copy from!");
                    }
                }

                CreateManagerPackage(gameName);

                AssetDatabase.SaveAssets();
                if (GameObject.FindObjectOfType <KickStarter>() == null)
                {
                    bool initScene = EditorUtility.DisplayDialog("Organise scene?", "Process complete.  Would you like to organise the scene objects to begin working?  This can be done at any time within the Scene Manager.", "Yes", "No");
                    if (initScene)
                    {
                        references.sceneManager.InitialiseObjects();
                    }
                }
            }
            catch (System.Exception e)
            {
                ACDebug.LogWarning("Could not create Manager. Does the subdirectory " + managerPath + " exist?");
                Debug.LogException(e, this);
                pageNumber--;
            }
        }
コード例 #9
0
        private void GenerateColliders()
        {
            HullPainter currentHullPainter = sceneManipulator.GetCurrentHullPainter();

            if (currentHullPainter == null)
            {
                return;
            }

            Undo.RegisterCompleteObjectUndo(currentHullPainter.gameObject, "Generate Colliders");

            // Fetch the data assets

            PaintingData paintingData = currentHullPainter.paintingData;
            HullData     hullData     = currentHullPainter.hullData;

            string hullAssetPath = AssetDatabase.GetAssetPath(hullData);

            // Create / update the hull meshes

            foreach (Hull hull in paintingData.hulls)
            {
                paintingData.GenerateCollisionMesh(hull, sceneManipulator.GetTargetVertices(), sceneManipulator.GetTargetTriangles());
            }

            // Sync the in-memory hull meshes with the asset meshes in hullAssetPath

            List <Mesh> existingMeshes = GetAllMeshesInAsset(hullAssetPath);

            foreach (Mesh existing in existingMeshes)
            {
                if (!paintingData.ContainsMesh(existing))
                {
                    GameObject.DestroyImmediate(existing, true);
                }
            }

            foreach (Hull hull in paintingData.hulls)
            {
                if (hull.collisionMesh != null)
                {
                    if (!existingMeshes.Contains(hull.collisionMesh))
                    {
                        AssetDatabase.AddObjectToAsset(hull.collisionMesh, hullAssetPath);
                    }
                }
                if (hull.faceCollisionMesh != null)
                {
                    if (existingMeshes.Contains(hull.faceCollisionMesh))
                    {
                        AssetDatabase.AddObjectToAsset(hull.faceCollisionMesh, hullAssetPath);
                    }
                }
            }

            EditorUtility.SetDirty(hullData);

            AssetDatabase.SaveAssets();

            // Add collider components to the target object

            currentHullPainter.CreateColliderComponents();
        }
コード例 #10
0
        public static void CreateFileForResult(List <Core_Voxel.Result> resultList, Shader shader, float scale, Vector3 pivot)
        {
            TheShader  = shader;
            ModelScale = scale;

            for (int index = 0; index < resultList.Count; index++)
            {
                var  result     = resultList[index];
                bool lod        = result.VoxelModels.Length > 1;
                bool isRig      = !lod && result.IsRigged;
                int  realLodNum = result.VoxelModels.Length;

                var         root         = new GameObject(result.FileName).transform;
                var         meshs        = new List <Mesh>();
                var         materialsMap = new Dictionary <Texture2D, Material>();
                Transform[] lodRoots     = new Transform[realLodNum];
                for (int lodIndex = 0; lodIndex < realLodNum; lodIndex++)
                {
                    var voxelModel = result.VoxelModels[lodIndex];
                    var model      = CreateModelFrom(voxelModel.RootNode, root, pivot, ref meshs, ref materialsMap, isRig, result.WithAvatar);
                    model.name         = string.Format("Root{0}", lod ? "_lod " + lodIndex.ToString() : "");
                    lodRoots[lodIndex] = model;


                    // Rig
                    if (isRig)
                    {
                        Vector3 halfModelSize = voxelModel.ModelSize[0] * 0.5f;
                        halfModelSize.x = Mathf.Floor(halfModelSize.x);
                        halfModelSize.y = Mathf.Floor(halfModelSize.y);
                        halfModelSize.z = Mathf.Floor(halfModelSize.z);

                        var skinMR = model.GetComponent <SkinnedMeshRenderer>();
                        if (skinMR)
                        {
                            Vector3 rootBoneOffset = halfModelSize * ModelScale;
                            var     boneTFList     = new List <Transform>();
                            if (voxelModel.RootBones != null)
                            {
                                for (int i = 0; i < voxelModel.RootBones.Length; i++)
                                {
                                    var boneTF = CreateBoneTransform(voxelModel.RootBones[i], model, ref boneTFList);
                                    if (boneTF)
                                    {
                                        boneTF.localPosition -= rootBoneOffset;
                                    }
                                }
                            }

                            skinMR.bones    = boneTFList.ToArray();
                            skinMR.rootBone = model;

                            // Bind Poses
                            var poses = new Matrix4x4[boneTFList.Count];
                            for (int i = 0; i < boneTFList.Count; i++)
                            {
                                poses[i] = boneTFList[i].worldToLocalMatrix * model.localToWorldMatrix;
                            }
                            skinMR.sharedMesh.bindposes = poses;
                        }

                        // Foot Fix
                        model.localPosition = (halfModelSize - voxelModel.FootPoints[lodIndex] + Vector3.up * 0.5f) * ModelScale;
                    }
                }



                // Lod
                if (lod)
                {
                    LODGroup group = root.gameObject.AddComponent <LODGroup>();
                    LOD[]    lods  = new LOD[realLodNum];
                    for (int i = 0; i < realLodNum; i++)
                    {
                        lods[i] = new LOD(
                            i == realLodNum - 1 ? 0.001f : GetLodRant(result.VoxelModels[i].MaxModelBounds, i),
                            lodRoots[i].GetComponentsInChildren <MeshRenderer>(true)
                            );
                    }
#if UNITY_5_0 || UNITY_5_1 || UNITY_4
                    group.SetLODS(lods);
                    group.RecalculateBounds();
#else
                    group.SetLODs(lods);
                    group.RecalculateBounds();
#endif
                }
                else if (!isRig && root.childCount > 0)
                {
                    var newRoot = root.GetChild(0);
                    newRoot.name = root.name;
                    root         = newRoot;
                }



                // File
                string path = Util.CombinePaths(
                    result.ExportRoot,
                    result.ExportSubRoot,
                    result.FileName + result.Extension
                    );
                path = Util.FixPath(path);
                string parentPath = Util.GetParentPath(path);
                Util.CreateFolder(parentPath);

                if (result.Extension == ".prefab")
                {
                    Object prefab;

                    if (Util.FileExists(path))
                    {
                        prefab = AssetDatabase.LoadAssetAtPath <Object>(path);
                        if (prefab as GameObject)
                        {
                            var group = (prefab as GameObject).GetComponent <LODGroup>();
                            if (group)
                            {
                                Object.DestroyImmediate(group, true);
                            }
                        }
                        Object[] things = AssetDatabase.LoadAllAssetRepresentationsAtPath(path);
                        foreach (Object o in things)
                        {
                            Object.DestroyImmediate(o, true);
                        }
                    }
                    else
                    {
                        prefab = PrefabUtility.CreateEmptyPrefab(path);
                    }

                    if (prefab)
                    {
                        // Assets
                        for (int i = 0; i < meshs.Count; i++)
                        {
                            meshs[i].name = GetIndexedName("Mesh", i, meshs.Count);
                            AssetDatabase.AddObjectToAsset(meshs[i], path);
                        }
                        int currentIndex = 0;
                        foreach (var textureMat in materialsMap)
                        {
                            textureMat.Key.name   = GetIndexedName("Texture", currentIndex, materialsMap.Count);
                            textureMat.Value.name = GetIndexedName("Material", currentIndex, materialsMap.Count);
                            currentIndex++;
                            AssetDatabase.AddObjectToAsset(textureMat.Key, path);
                            AssetDatabase.AddObjectToAsset(textureMat.Value, path);
                        }

                        // Avatar
                        if (isRig && result.WithAvatar)
                        {
                            var avatar = GetVoxelAvatarInRoot(root);
                            if (avatar)
                            {
                                avatar.name = result.FileName;
                                AssetDatabase.AddObjectToAsset(avatar, path);

                                // Animator
                                var ani = root.GetComponent <Animator>();
                                if (!ani)
                                {
                                    ani = root.gameObject.AddComponent <Animator>();
                                }
                                ani.avatar = avatar;
                            }
                        }

                        // Prefab
                        PrefabUtility.ReplacePrefab(root.gameObject, prefab, ReplacePrefabOptions.ReplaceNameBased);
                    }
                }
                else                     // Obj

                {
                    string objFolderPath     = Util.CombinePaths(parentPath, result.FileName);
                    string textureFolderPath = Util.CombinePaths(objFolderPath, "Textures");
                    Util.CreateFolder(objFolderPath);

                    VoxelPostprocessor.TheShader = TheShader;

                    // Assets
                    var model = result.VoxelModels[0];
                    for (int modelIndex = 0; modelIndex < model.Meshs.Length; modelIndex++)
                    {
                        string modelIndexedName = GetIndexedName(result.FileName, modelIndex, model.Meshs.Length);
                        string modelPathRoot    = Util.CombinePaths(objFolderPath, modelIndexedName);

                        // Texture
                        string texturePath = Util.CombinePaths(textureFolderPath, modelIndexedName + ".png");
                        texturePath = Util.FixPath(texturePath);
                        var texture = model.Textures[modelIndex];
                        Util.ByteToFile(texture.EncodeToPNG(), texturePath);
                        VoxelPostprocessor.AddTexture(texturePath);

                        // Meshs
                        var uMesh = model.Meshs[modelIndex];
                        for (int i = 0; i < uMesh.Count; i++)
                        {
                            uMesh[i].name = GetIndexedName("Mesh", i, uMesh.Count);
                            string obj     = Util.GetObj(uMesh[i]);
                            string objPath = GetIndexedName(modelPathRoot, i, uMesh.Count) + ".obj";

                            bool hasObjBefore = Util.FileExists(objPath);

                            Util.Write(obj, objPath);
                            VoxelPostprocessor.AddObj(objPath, texturePath);

                            if (hasObjBefore)
                            {
                                AssetDatabase.ImportAsset(Util.FixedRelativePath(objPath), ImportAssetOptions.ForceUpdate);
                            }
                        }
                    }
                }


                // Delete Objects
                if (root.parent)
                {
                    Object.DestroyImmediate(root.parent.gameObject, false);
                }
                else
                {
                    Object.DestroyImmediate(root.gameObject, false);
                }
            }
            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
            AssetDatabase.SaveAssets();
            Resources.UnloadUnusedAssets();

            EditorApplication.delayCall += VoxelPostprocessor.ClearAsset;
        }
コード例 #11
0
        public void BuildPlaybackPrefab(ProgressBar progress)
        {
            var timeline = ScriptableObject.CreateInstance <TimelineAsset>();

            var animationTrack = timeline.CreateTrack <AnimationTrack>(null, "Playback Animation");

            var clip = generateCompressedClip(progress);

            var playableAsset = ScriptableObject.CreateInstance <AnimationPlayableAsset>();

            playableAsset.clip      = clip;
            playableAsset.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
            playableAsset.name      = "Recorded Animation";

            var timelineClip = animationTrack.CreateClip(clip);

            timelineClip.duration    = clip.length;
            timelineClip.asset       = playableAsset;
            timelineClip.displayName = "Recorded Animation";

            //If a clip is not recordable, it will not show up as editable in the timeline view.
            //For whatever reason unity decided that imported clips are not recordable, so we hack a
            //private variable to force them to be!  This seems to have no ill effects but if things go
            //wrong we can just revert this line
            timelineClip.GetType().GetField("m_Recordable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(timelineClip, true);

            //Try to generate a leap recording if we have leap data
            RecordingTrack recordingTrack = null;
            LeapRecording  leapRecording  = null;

            string framesPath = Path.Combine(dataFolder.Path, "Frames.data");

            if (File.Exists(framesPath))
            {
                List <Frame> frames = new List <Frame>();

                progress.Begin(1, "Loading Leap Data", "", () => {
                    progress.Step();
                    using (var reader = File.OpenText(framesPath)) {
                        while (true)
                        {
                            string line = reader.ReadLine();
                            if (string.IsNullOrEmpty(line))
                            {
                                break;
                            }

                            frames.Add(JsonUtility.FromJson <Frame>(line));
                        }
                    }
                });

                leapRecording = ScriptableObject.CreateInstance(_leapRecordingType) as LeapRecording;
                if (leapRecording != null)
                {
                    leapRecording.name = "Recorded Leap Data";
                    leapRecording.LoadFrames(frames);
                }
                else
                {
                    Debug.LogError("Unable to create Leap recording: Invalid type specification for "
                                   + "LeapRecording implementation.", this);
                }
            }

            string assetPath = Path.Combine(assetFolder.Path, recordingName + ".asset");

            AssetDatabase.CreateAsset(timeline, assetPath);
            AssetDatabase.AddObjectToAsset(playableAsset, timeline);
            AssetDatabase.AddObjectToAsset(animationTrack, timeline);
            AssetDatabase.AddObjectToAsset(clip, timeline);

            //If we do have a leap recording, create a recording track to house it
            if (leapRecording != null)
            {
                recordingTrack = timeline.CreateTrack <RecordingTrack>(null, "Leap Recording");

                var recordingClip = recordingTrack.CreateDefaultClip();
                recordingClip.duration = leapRecording.length;

                var recordingAsset = recordingClip.asset as RecordingClip;
                recordingAsset.recording = leapRecording;

                AssetDatabase.AddObjectToAsset(leapRecording, timeline);
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            //Create the playable director and link it to the new timeline
            var director = gameObject.AddComponent <PlayableDirector>();

            director.playableAsset = timeline;

            //Create the animator
            gameObject.AddComponent <Animator>();

            //Link the animation track to the animator
            //(it likes to point to gameobject instead of the animator directly)
            director.SetGenericBinding(animationTrack.outputs.Query().First().sourceObject, gameObject);

            //Destroy existing provider
            var provider = gameObject.GetComponentInChildren <LeapProvider>();

            if (provider != null)
            {
                GameObject providerObj = provider.gameObject;
                DestroyImmediate(provider);
                //If a leap recording track exists, spawn a playable provider and link it to the track
                if (recordingTrack != null)
                {
                    var playableProvider = providerObj.AddComponent <LeapPlayableProvider>();
                    director.SetGenericBinding(recordingTrack.outputs.Query().First().sourceObject, playableProvider);
                }
            }

            buildAudioTracks(progress, director, timeline);
            buildMethodRecordingTracks(progress, director, timeline);

            progress.Begin(1, "", "Finalizing Prefab", () => {
                GameObject myGameObject = gameObject;
                DestroyImmediate(this);

                string prefabPath = Path.Combine(assetFolder.Path, recordingName + ".prefab");
                PrefabUtility.SaveAsPrefabAsset(myGameObject, prefabPath.Replace('\\', '/'));
            });
        }
コード例 #12
0
ファイル: PCommon.cs プロジェクト: ComradeCrunchy/Ranch
        public static void AddObjectToAsset(Object objectToAdd, Object asset)
        {
#if UNITY_EDITOR
            AssetDatabase.AddObjectToAsset(objectToAdd, asset);
#endif
        }
コード例 #13
0
        void DrawProfileInspectorGUI()
        {
            EditorGUILayout.Space();

            bool assetHasChanged = false;
            bool showCopy        = m_Profile.objectReferenceValue != null;

            // The layout system sort of break alignement when mixing inspector fields with custom
            // layouted fields, do the layout manually instead
            int   buttonWidth    = showCopy ? 45 : 60;
            float indentOffset   = EditorGUI.indentLevel * 15f;
            var   lineRect       = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight);
            var   labelRect      = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height);
            var   fieldRect      = new Rect(labelRect.xMax, lineRect.y, lineRect.width - labelRect.width - buttonWidth * (showCopy ? 2 : 1), lineRect.height);
            var   buttonNewRect  = new Rect(fieldRect.xMax, lineRect.y, buttonWidth, lineRect.height);
            var   buttonCopyRect = new Rect(buttonNewRect.xMax, lineRect.y, buttonWidth, lineRect.height);

            EditorGUI.PrefixLabel(labelRect, m_ProfileLabel);

            using (var scope = new EditorGUI.ChangeCheckScope())
            {
                m_Profile.objectReferenceValue
                    = (PostProcessProfile)EditorGUI.ObjectField(
                          fieldRect, m_Profile.objectReferenceValue, typeof(PostProcessProfile), false);
                assetHasChanged = scope.changed;
            }

            if (GUI.Button(
                    buttonNewRect,
                    EditorUtilities.GetContent("New|Create a new profile."),
                    showCopy ? EditorStyles.miniButtonLeft : EditorStyles.miniButton))
            {
                // By default, try to put assets in a folder next to the currently active
                // scene file. If the user isn't a scene, put them in root instead.
                var targetName = Target.name;
                var scene      = Target.gameObject.scene;
                var asset      = CreatePostProcessProfile(scene, targetName);
                m_Profile.objectReferenceValue = asset;
                assetHasChanged = true;
            }

            if (showCopy && GUI.Button(
                    buttonCopyRect,
                    EditorUtilities.GetContent("Clone|Create a new profile and copy the content of the currently assigned profile."),
                    EditorStyles.miniButtonRight))
            {
                // Duplicate the currently assigned profile and save it as a new profile
                var origin = (PostProcessProfile)m_Profile.objectReferenceValue;
                var path   = AssetDatabase.GetAssetPath(origin);
                path = AssetDatabase.GenerateUniqueAssetPath(path);

                var asset = Instantiate(origin);
                asset.settings.Clear();
                AssetDatabase.CreateAsset(asset, path);

                foreach (var item in origin.settings)
                {
                    var itemCopy = Instantiate(item);
                    itemCopy.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
                    itemCopy.name      = item.name;
                    asset.settings.Add(itemCopy);
                    AssetDatabase.AddObjectToAsset(itemCopy, asset);
                }

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                m_Profile.objectReferenceValue = asset;
                assetHasChanged = true;
            }

            if (m_Profile.objectReferenceValue == null)
            {
                if (assetHasChanged && m_EffectList != null)
                {
                    m_EffectList.Clear(); // Asset wasn't null before, do some cleanup
                }
                EditorGUILayout.HelpBox(
                    "Assign an existing Post-process Profile by choosing an asset, or create a new one by clicking the \"New\" button.\nNew assets are automatically put in a folder next to your scene file. If your scene hasn't been saved yet they will be created at the root of the Assets folder.",
                    MessageType.Info);
            }
            else
            {
                if (assetHasChanged)
                {
                    RefreshEffectListEditor((PostProcessProfile)m_Profile.objectReferenceValue);
                }
                if (m_EffectList != null)
                {
                    m_EffectList.OnGUI();
                }
            }
        }
コード例 #14
0
ファイル: AutoLOD.cs プロジェクト: tsantarra/AutoLOD
        static void GenerateLODs(GameObject go)
        {
            // A NOP to make sure we have an instance before launching into threads that may need to execute on the main thread
            MonoBehaviourHelper.ExecuteOnMainThread(() => {});

            var meshFilters = go.GetComponentsInChildren <MeshFilter>();

            if (meshFilters.Length > 0)
            {
                var lodGroup = go.GetComponent <LODGroup>();
                if (!lodGroup)
                {
                    lodGroup = go.AddComponent <LODGroup>();
                }

                var lods = new LOD[maxLOD + 1];
                var lod0 = lods[0];
                lod0.renderers = go.GetComponentsInChildren <MeshRenderer>();
                lod0.screenRelativeTransitionHeight = 0.5f;
                lods[0] = lod0;

                var meshes = new List <Mesh>();

                for (int l = 1; l <= maxLOD; l++)
                {
                    var lodRenderers = new List <MeshRenderer>();
                    foreach (var mf in meshFilters)
                    {
                        var sharedMesh = mf.sharedMesh;

                        if (!sharedMesh)
                        {
                            Debug.LogWarning("AutoLOD: Missing mesh " + mf.name, mf);
                            continue;
                        }

                        var lodTransform = EditorUtility.CreateGameObjectWithHideFlags(string.Format("{0} LOD{1}", sharedMesh.name, l),
                                                                                       k_DefaultHideFlags, typeof(MeshFilter), typeof(MeshRenderer)).transform;
                        lodTransform.SetParent(mf.transform, false);

                        var lodMF       = lodTransform.GetComponent <MeshFilter>();
                        var lodRenderer = lodTransform.GetComponent <MeshRenderer>();

                        lodRenderers.Add(lodRenderer);

                        EditorUtility.CopySerialized(mf, lodMF);
                        EditorUtility.CopySerialized(mf.GetComponent <MeshRenderer>(), lodRenderer);

                        var simplifiedMesh = new Mesh();
                        simplifiedMesh.name = sharedMesh.name + string.Format(" LOD{0}", l);
                        lodMF.sharedMesh    = simplifiedMesh;
                        meshes.Add(simplifiedMesh);

                        var meshLOD = MeshLOD.GetGenericInstance(meshSimplifierType);
                        meshLOD.InputMesh  = sharedMesh;
                        meshLOD.OutputMesh = simplifiedMesh;
                        meshLOD.Quality    = Mathf.Pow(0.5f, l);
                        meshLOD.Generate();
                    }

                    var lod = lods[l];
                    lod.renderers = lodRenderers.ToArray();
                    lod.screenRelativeTransitionHeight = l == maxLOD ? 0.01f : Mathf.Pow(0.5f, l + 1);
                    lods[l] = lod;
                }

                lodGroup.ForceLOD(0);
                lodGroup.SetLODs(lods.ToArray());
                lodGroup.RecalculateBounds();
                lodGroup.ForceLOD(-1);

#if UNITY_2018_2_OR_NEWER
                var prefab = PrefabUtility.GetCorrespondingObjectFromSource(go);
#else
                var prefab = PrefabUtility.GetPrefabParent(go);
#endif
                if (prefab)
                {
                    var lodsAssetPath = GetLODAssetPath(prefab);
                    if (File.Exists(lodsAssetPath))
                    {
                        meshes.ForEach(m => AssetDatabase.AddObjectToAsset(m, lodsAssetPath));
                    }
                    else
                    {
                        ObjectUtils.CreateAssetFromObjects(meshes.ToArray(), lodsAssetPath);
                    }
                }
            }
        }
コード例 #15
0
    static public void Setup(string testType, string pathFormat, string suffix)
    {
#if UNITY_EDITOR
        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);
#endif
    }
コード例 #16
0
        private void ResetActionList()
        {
            SerializedObject   obj      = new SerializedObject(state);
            SerializedProperty elements = obj.FindProperty("actions");

            actionList = new ReorderableObjectList(obj, elements);

            actionList.drawHeaderCallback = delegate(Rect rect) {
                EditorGUI.LabelField(rect, "Actions");
            };

            actionList.onAddCallback = delegate(ReorderableObjectList list) {
                FsmGUIUtility.SubclassMenu <StateAction> (delegate(Type type){
                    StateAction action = (StateAction)ScriptableObject.CreateInstance(type);
                    action.name        = type.GetCategory() + "." + type.Name;
                    action.hideFlags   = HideFlags.HideInHierarchy;
                    state.Actions      = ArrayUtility.Add <StateAction> (state.Actions, action);

                    if (EditorUtility.IsPersistent(state))
                    {
                        AssetDatabase.AddObjectToAsset(action, state);
                        AssetDatabase.SaveAssets();
                    }
                    list.index = list.count;
                    EditorUtility.SetDirty(state);
                });
            };

            actionList.drawElementCallback = delegate(int index, bool selected) {
                StateAction action  = state.Actions [index];
                bool        enabled = action.IsEnabled;
                if (selected)
                {
                    GUIStyle selectBackground = new GUIStyle("MeTransitionSelectHead")
                    {
                        stretchHeight = false,
                    };
                    selectBackground.overflow = new RectOffset(-1, -2, -2, 2);
                    GUILayout.BeginVertical(selectBackground);
                }
                action.IsOpen = GUIDrawer.ObjectTitlebar(action, action.IsOpen, ref enabled, FsmGUIUtility.ExecutableContextMenu(action, state));
                if (selected)
                {
                    GUILayout.EndVertical();
                }
                action.IsEnabled = enabled;
                if (action.IsOpen)
                {
                    GUIDrawer.OnGUI(action);
                }
            };

            actionList.onRemoveCallback = delegate(ReorderableObjectList list) {
                StateAction action = state.Actions[list.index];
                state.Actions = ArrayUtility.Remove <StateAction> (state.Actions, action);
                FsmEditorUtility.DestroyImmediate(action);
                list.index = list.index - 1;
                ErrorChecker.CheckForErrors();
                EditorUtility.SetDirty(state);
            };

            actionList.onContextClick = delegate(int index) {
                FsmGUIUtility.ExecutableContextMenu(state.Actions [index], state).ShowAsContext();
            };

            actionList.onHeaderContextClick = delegate() {
                GenericMenu menu = new GenericMenu();

                if (state.Actions.Length > 0)
                {
                    menu.AddItem(new GUIContent("Copy"), false, delegate {
                        copy      = new List <StateAction>(state.Actions);
                        copyState = state;
                    });
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Copy"));
                }

                if (copy == null)
                {
                    copy = new List <StateAction>();
                }

                copy.RemoveAll(x => x == null);
                if (copy.Count > 0)
                {
                    menu.AddItem(new GUIContent("Paste After"), false, delegate() {
                        for (int i = 0; i < copy.Count; i++)
                        {
                            ExecutableNode dest = FsmUtility.Copy(copy[i]);
                            state.Actions       = ArrayUtility.Add <StateAction>(state.Actions, (StateAction)dest);
                            FsmEditorUtility.ParentChilds(state);
                            EditorUtility.SetDirty(state);
                            //	NodeInspector.Dirty();
                            ErrorChecker.CheckForErrors();
                        }
                    });
                    menu.AddItem(new GUIContent("Paste Before"), false, delegate() {
                        for (int i = 0; i < copy.Count; i++)
                        {
                            ExecutableNode dest = FsmUtility.Copy(copy[i]);
                            state.Actions       = ArrayUtility.Insert <StateAction>(state.Actions, (StateAction)dest, 0);
                            FsmEditorUtility.ParentChilds(state);
                            EditorUtility.SetDirty(state);
                            //	NodeInspector.Dirty();
                            ErrorChecker.CheckForErrors();
                        }
                    });
                    if (copyState != state)
                    {
                        menu.AddItem(new GUIContent("Replace"), false, delegate() {
                            for (int i = 0; i < state.Actions.Length; i++)
                            {
                                FsmEditorUtility.DestroyImmediate(state.Actions[i]);
                            }
                            state.Actions = new StateAction[0];
                            ResetActionList();

                            for (int i = 0; i < copy.Count; i++)
                            {
                                ExecutableNode dest = FsmUtility.Copy(copy[i]);
                                state.Actions       = ArrayUtility.Add <StateAction>(state.Actions, (StateAction)dest);
                                FsmEditorUtility.ParentChilds(state);
                                EditorUtility.SetDirty(state);
                                //	NodeInspector.Dirty();
                                ErrorChecker.CheckForErrors();
                            }
                        });
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent("Replace"));
                    }
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Paste After"));
                    menu.AddDisabledItem(new GUIContent("Paste Before"));
                    menu.AddDisabledItem(new GUIContent("Replace"));
                }
                menu.ShowAsContext();
            };

            this.host.Repaint();
            if (FsmEditor.instance != null)
            {
                FsmEditor.instance.Repaint();
            }
        }
コード例 #17
0
        public override void OnInspectorGUI()
        {
            //serializedObject.Update ();

            sequence = sequenceSerialziedProperty.objectReferenceValue as Sequence;

            EditorGUI.BeginChangeCheck();

            if (sequence != null)
            {
                wrapSerializedProperty.enumValueIndex = (int)sequence.wrap;
                EditorGUILayout.PropertyField(wrapSerializedProperty, wrapCurrentGUIContent);
                sequence.wrap = (Sequence.SequenceWrap)wrapSerializedProperty.enumValueIndex;
            }
            EditorGUILayout.PropertyField(playOnStartSerializedProperty, playOnStartGUIContent);



            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.PropertyField(sequenceSerialziedProperty, sequenceGUIContent);

            if (GUILayout.Button(cloneSequenceGUIContent))
            {
                if (sequence != null)
                {
                    Sequence sequenceNew = ScriptableObject.CreateInstance <Sequence>();



                    EditorUtilityEx.CreateAssetFromInstance(sequenceNew);

                    foreach (SequenceChannel channel in sequence.channels)
                    {
                        SequenceChannel channelClone = UnityEngine.Object.Instantiate <SequenceChannel>(channel);
                        channelClone.nodes.Clear();
                        sequenceNew.channels.Add(channelClone);
                        channelClone.sequence = sequenceNew;
                        AssetDatabase.AddObjectToAsset(channelClone, sequenceNew);

                        foreach (SequenceNode node in channel.nodes)
                        {
                            SequenceNode nodeClone = UnityEngine.Object.Instantiate <SequenceNode>(node);
                            nodeClone.channel = channelClone;
                            channelClone.nodes.Add(nodeClone);
                            AssetDatabase.AddObjectToAsset(nodeClone, channelClone);

                            EditorClipBinding clipBindingClone = UnityEngine.Object.Instantiate <EditorClipBinding>(node.clipBinding);
                            nodeClone.clipBinding = clipBindingClone;
                            AssetDatabase.AddObjectToAsset(clipBindingClone, nodeClone);
                        }
                    }
                }
            }
            EditorGUILayout.EndHorizontal();



            if (sequence != null)
            {
                timeCurrentSerializedProperty.floatValue = (float)sequence.timeCurrent;
                timeCurrentSerializedProperty.serializedObject.ApplyModifiedProperties();

                EditorGUILayout.Slider(timeCurrentSerializedProperty, (float)sequence.timeStart, (float)sequence.timeEnd);

                sequence.timeCurrent = timeCurrentSerializedProperty.floatValue;



                EditorGUILayout.BeginHorizontal();

                if (GUILayout.Button("Goto"))
                {
                    sequence.GoTo(timeCurrentSerializedProperty.floatValue);
                }


                if (GUILayout.Button(!Application.isPlaying ? (sequence.isPlaying ? "Pause" : "Play Forward") : "Play Forward"))
                {
                    if (Application.isPlaying)
                    {
                        sequence.Play(sequence.timeCurrent);
                    }
                    else
                    {
                        SequenceEditorWindow.Play();
                    }
                }

                if (GUILayout.Button("Play Backward"))
                {
                    if (Application.isPlaying)
                    {
                        sequence.Play(sequence.timeCurrent, false);
                    }
                    else
                    {
                        SequenceEditorWindow.Play(false);
                    }
                }

                if (GUILayout.Button("Stop"))
                {
                    if (Application.isPlaying)
                    {
                        sequence.Stop();
                    }
                    else
                    {
                        SequenceEditorWindow.Stop();
                    }
                }

                if (Application.isPlaying)
                {
                    if (GUILayout.Button("Pause"))
                    {
                        Debug.LogWarning("Not yet tested, not finished");

                        sequence.Pause();
                    }
                }

                if (Application.isPlaying)
                {
                    if (GUILayout.Button("UnPause"))
                    {
                        Debug.LogWarning("Not yet tested, not finished");
                        sequence.UnPause();
                    }
                }

                if (!Application.isPlaying)
                {
                    if (GUILayout.Button("Open Editor"))
                    {
                        SequenceEditorWindow.ShowWindow();
                    }
                }

                EditorGUILayout.EndHorizontal();


                if (EditorGUI.EndChangeCheck())
                {
                    serializedObject.ApplyModifiedProperties();

                    SequenceEditorWindow.window.Repaint();
                }

                //EditorUtilityEx.GetDrawer(typeof(UnityEngine.Events.UnityEventBase)).


                ///// DRAW SELECTED NODE (inside SequenceEditor) ////////
                SequenceNode selectedNode = sequence.nodeSelected;
                if (selectedNode != null)
                {
                    if (selectedNode != selectedNodePrev)
                    {
                        EditorGUILayout.Space();
                        EditorGUILayout.LabelField("Selected Node");
                        EditorGUILayout.Space();
                        nodeEditor = Editor.CreateEditor(selectedNode, typeof(SequenceNodeEditor)) as SequenceNodeEditor;
                        EditorGUILayout.Space();
                    }


                    nodeEditor.OnInspectorGUI();
                }
                else
                {
                    EditorGUILayout.LabelField("No Node selected");
                }

                selectedNodePrev = selectedNode;
            }
        }
コード例 #18
0
        void OnEnable()
        {
            if (SceneView.sceneViews.Count > 0)
            {
                SceneView sceneView = (SceneView)SceneView.sceneViews[0];
                sceneView.Focus();
            }

            m_WalkableArea = (WalkableArea)target;

            m_Sprite            = serializedObject.FindProperty("m_sprite");
            m_NavMeshData       = serializedObject.FindProperty("m_NavMeshData");
            m_Detail            = serializedObject.FindProperty("m_detail");
            m_Color             = serializedObject.FindProperty("m_color");
            m_AgentTypeID       = serializedObject.FindProperty("m_AgentTypeID");
            m_BuildHeightMesh   = serializedObject.FindProperty("m_BuildHeightMesh");
            m_DefaultArea       = serializedObject.FindProperty("m_DefaultArea");
            m_LayerMask         = serializedObject.FindProperty("m_LayerMask");
            m_OverrideTileSize  = serializedObject.FindProperty("m_OverrideTileSize");
            m_OverrideVoxelSize = serializedObject.FindProperty("m_OverrideVoxelSize");
            m_TileSize          = serializedObject.FindProperty("m_TileSize");
            m_VoxelSize         = serializedObject.FindProperty("m_VoxelSize");

            Mesh collisionMesh = new Mesh();

            collisionMesh.vertices = new[]
            {
                new Vector3(-1.0f, -0.1f, -1.0f),
                new Vector3(1.0f, -0.1f, -1.0f),
                new Vector3(-1.0f, -0.1f, 1.0f),
                new Vector3(1.0f, -0.1f, 1.0f)
            };
            collisionMesh.triangles = new[]
            {
                0, 2, 1,
                2, 3, 1
            };
            collisionMesh.normals = new[]
            {
                -Vector3.forward,
                -Vector3.forward,
                -Vector3.forward,
                -Vector3.forward
            };
            collisionMesh.uv = new[]
            {
                new Vector2(0, 0),
                new Vector2(1, 0),
                new Vector2(0, 1),
                new Vector2(1, 1)
            };

            m_CollisionMeshMaterial = new Material(Shader.Find("UI/Default"));

            m_CollisionObject = new GameObject("__CollisionObject__");
            m_CollisionObject.transform.SetParent(m_WalkableArea.transform, false);
            m_CollisionObject.transform.localPosition = new Vector3(0.0f, 10.0f, 0.0f);
            m_CollisionObject.hideFlags = HideFlags.HideAndDontSave;

            MeshFilter   meshFilter   = m_CollisionObject.AddComponent <MeshFilter>();
            MeshRenderer meshRenderer = m_CollisionObject.AddComponent <MeshRenderer>();
            MeshCollider meshCollider = m_CollisionObject.AddComponent <MeshCollider>();

            meshFilter.mesh         = collisionMesh;
            meshCollider.sharedMesh = collisionMesh;
            meshRenderer.material   = m_CollisionMeshMaterial;

            if (SceneManager.Instance == null)
            {
                Debug.LogError("Could not find SceneManager as parent of SpriteMesh!");
                return;
            }

            if (m_WalkableArea.m_sprite == null)
            {
                GameObject root       = PrefabUtility.FindValidUploadPrefabInstanceRoot(m_WalkableArea.transform.parent.gameObject);
                string     spritePath = Path.Combine(Path.Combine(SceneManager.Instance.m_outputPath, root.name), "Editor");
                Directory.CreateDirectory(spritePath);
                string spriteAssetPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(spritePath, string.Format("{0}.png", m_WalkableArea.name)));

                // load the sprite or create it if it doesn't exist
                m_WalkableArea.m_sprite = AssetDatabase.LoadAssetAtPath <Sprite>(spriteAssetPath);
                if (m_WalkableArea.m_sprite == null)
                {
                    // create the texture if it doesn't exist
                    Texture2D texture = AssetDatabase.LoadAssetAtPath <Texture2D>(spriteAssetPath);
                    if (texture == null)
                    {
                        Directory.CreateDirectory(spritePath);

                        WalkableAreaGroup group = m_WalkableArea.transform.parent.gameObject.GetComponent <WalkableAreaGroup>();

                        m_PaintTexture = new Texture2D(group.m_textureWidth, group.m_textureHeight, TextureFormat.RGBA32, false);
                        Color[] colors = m_PaintTexture.GetPixels();
                        for (int i = 0; i < colors.Length; ++i)
                        {
                            colors[i] = k_TransparentWhite;
                        }
                        m_PaintTexture.SetPixels(colors);
                        byte[] bytes = m_PaintTexture.EncodeToPNG();
                        File.WriteAllBytes(spriteAssetPath, bytes);
                        AssetDatabase.Refresh();
                    }
                    ResetTextureImporterSettings(spriteAssetPath);

                    Sprite sprite = Sprite.Create(m_PaintTexture, new Rect(0.0f, 0.0f, m_PaintTexture.width, m_PaintTexture.height), new Vector2(0.5f, 0.5f));
                    AssetDatabase.AddObjectToAsset(sprite, spriteAssetPath);
                    AssetDatabase.SaveAssets();

                    m_WalkableArea.m_sprite = AssetDatabase.LoadAssetAtPath <Sprite>(spriteAssetPath);
                }
            }

            m_PaintTexture = new Texture2D(m_WalkableArea.m_sprite.texture.width, m_WalkableArea.m_sprite.texture.height, TextureFormat.RGBA32, false);

            string          texturePath = AssetDatabase.GetAssetPath(m_WalkableArea.m_sprite);
            TextureImporter importer    = AssetImporter.GetAtPath(texturePath) as TextureImporter;

            if (importer != null)
            {
                if (importer.DoesSourceTextureHaveAlpha())
                {
                    Graphics.CopyTexture(m_WalkableArea.m_sprite.texture, m_PaintTexture);
                }
                else
                {
                    Graphics.ConvertTexture(m_WalkableArea.m_sprite.texture, m_PaintTexture);
                }
            }

            Tools.hidden = true;
        }
コード例 #19
0
        public static void OnPrefabSaving(GameObject obj)
        {
            var foundGeneratedMeshes = obj.GetComponentsInChildren <GeneratedMeshes>();

            if (foundGeneratedMeshes.Length == 0)
            {
                return;
            }

            var defaultModel = InternalCSGModelManager.GetDefaultCSGModelForObject(obj.transform);

            newMeshes.Clear();
            foreach (var generatedMeshesInstance in foundGeneratedMeshes)
            {
                if (generatedMeshesInstance.owner == defaultModel)
                {
                    continue;
                }

                foreach (var generatedMeshInstance in generatedMeshesInstance.GetComponentsInChildren <GeneratedMeshInstance>())
                {
                    if (!generatedMeshInstance) // possible when it's deleted in a prefab
                    {
                        continue;
                    }
                    foundGeneratedMeshInstances.Add(generatedMeshInstance);
                    if (generatedMeshInstance.SharedMesh)
                    {
                        newMeshes.Add(generatedMeshInstance.SharedMesh);
                    }
                }

                foreach (var helperSurface in generatedMeshesInstance.HelperSurfaces)
                {
                    foundHelperSurfaces.Add(helperSurface);
                    newMeshes.Add(helperSurface.SharedMesh);
                }
            }

            var asset     = CSGPrefabUtility.GetPrefabAsset(obj);
            var assetPath = AssetDatabase.GetAssetPath(asset);

            var assetObjects = AssetDatabase.LoadAllAssetsAtPath(assetPath);

            foreach (var assetObject in assetObjects)
            {
                var mesh = assetObject as Mesh;
                if (!mesh)
                {
                    continue;
                }
                oldMeshes.Add(mesh);
            }

            if (newMeshes.Count == 0 && oldMeshes.Count == 0)
            {
                return;
            }

            // We might be modifying a prefab, in which case we need to store meshes inside it that belong to it
            AssetDatabase.StartAssetEditing();
            try
            {
                foreach (var oldMesh in oldMeshes)
                {
                    if (newMeshes.Contains(oldMesh))
                    {
                        continue;
                    }

                    if (CanRemoveObjectFromAsset(assetPath, oldMesh, ignoreWhenPartOfOtherAsset: true))
                    {
                        AssetDatabase.RemoveObjectFromAsset(oldMesh);
                    }
                }

                foreach (var _newMesh in newMeshes)
                {
                    var newMesh = _newMesh;
                    if (oldMeshes.Contains(newMesh))
                    {
                        if (IsObjectPartOfAsset(assetPath, newMesh))
                        {
                            continue;
                        }
                    }
                    if (CanAddObjectToAsset(assetPath, newMesh))
                    {
                        AssetDatabase.AddObjectToAsset(newMesh, asset);
                    }
                }
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
            }
        }
コード例 #20
0
        public static bool ApplyTexture2DArray(Texture2DArrayManager manager)
        {
            Texture2D[] tex2DArray = Array.FindAll(manager.textureInputArray, tex => tex != null);

            if (tex2DArray.Length <= 0)
            {
                errorBuilder.Remove(0, errorBuilder.Length);
                Array.ForEach(tex2DArray, (tex) => errorBuilder.Append(tex.name).Append(" : ").Append(tex.width).Append(',').Append(tex.height).Append('\n'));

                Debug.LogErrorFormat("Fail to apply.. not exist texture in array.");
                return(false);
            }

            Texture2D firstTex = tex2DArray[0];
            int       width = firstTex.width, height = firstTex.height;

            if (!Array.TrueForAll(tex2DArray, (tex) => tex.width == width && tex.height == height))
            {
                errorBuilder.Remove(0, errorBuilder.Length);
                Array.ForEach(tex2DArray, (tex) => errorBuilder.Append(tex.name).Append(" : ").Append(tex.width).Append(',').Append(tex.height).Append('\n'));

                Debug.LogErrorFormat("Fail to apply.. all texture size must be same.\n{0}", errorBuilder.ToString());
                return(false);
            }

            TextureFormat format = firstTex.format;

            if (!Array.TrueForAll(tex2DArray, (tex) => tex.format == format))
            {
                format = TextureFormat.RGBA32;

                errorBuilder.Remove(0, errorBuilder.Length);
                Array.ForEach(tex2DArray, (tex) => errorBuilder.Append(tex.name).Append(" : ").Append(tex.format).Append('\n'));

                Debug.LogWarningFormat("All texture format is not same. Force {0}.{1} \n{2}", format.GetType().ToString(), format.ToString(), errorBuilder.ToString());
            }

            Texture2DArray realArray = manager.texture2DArray;

            if (IsDifferent(manager))
            {
                DestroyImmediate(manager.texture2DArray, true);

                realArray      = new Texture2DArray(width, height, tex2DArray.Length, format, false);
                realArray.name = "Texture2DArray";

                AssetDatabase.AddObjectToAsset(realArray, manager);

                manager.texture2DArray = realArray;

                Debug.LogWarning("Texture2DArray instance is re-created.");
            }

            for (int i = 0; i < tex2DArray.Length; i++)
            {
                for (int j = 0; j < tex2DArray[i].mipmapCount; j++)
                {
                    Graphics.CopyTexture(tex2DArray[i], 0, j, realArray, i, j);
                }
            }

            realArray.Apply(true);

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(manager));
            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);

            return(true);
        }
コード例 #21
0
ファイル: SDFGenerator.cs プロジェクト: studentutu/DFAO-unity
        //TODO improve asset saving
        private void BakeComplete(SDFVolume sdfVolume, float[] distances, float maxDistance, object passthrough)
        {
            //update the bounds since they may have been adjusted during bake
            bounds = sdfVolume.Settings.BoundsLocal;

            string path = "";

            if (sdfData != null)
            {
                //use path of existing sdfData
                path = AssetDatabase.GetAssetPath(sdfData);

                //check if asset at path
                Object obj = AssetDatabase.LoadAssetAtPath <SDFData>(path);
                if (obj != null)
                {
                    if ((( SDFData )obj).sdfTexture != null)
                    {
                        //destroy old texture
                        Object.DestroyImmediate((( SDFData )obj).sdfTexture, true);
                    }
                    //destroy old asset
                    //TODO this will break references...
                    Object.DestroyImmediate(obj, true);
                }
            }

            // If not exisiting asset get path to save sdfData to.
            if (string.IsNullOrEmpty(path))
            {
                string suggestedName = "sdfData_" + this.name;

                path = EditorUtility.SaveFilePanelInProject("Save As...", suggestedName, "asset", "Save the SDF Data");

                if (string.IsNullOrEmpty(path))
                {
                    if (EditorUtility.DisplayDialog("Error", "Path was invalid, retry?", "ok", "cancel"))
                    {
                        path = EditorUtility.SaveFilePanelInProject("Save As...", suggestedName, "asset", "Save the SDF Data");
                    }

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


            //create new SDFData
            sdfData            = ScriptableObject.CreateInstance <SDFData>();
            sdfData.bounds     = sdfVolume.Settings.BoundsLocal;
            sdfData.voxelSize  = sdfVolume.Settings.VoxelSize;
            sdfData.dimensions = sdfVolume.Settings.Dimensions;

            float minAxis = Mathf.Min(sdfData.bounds.size.x, Mathf.Min(sdfData.bounds.size.y, sdfData.bounds.size.z));

            sdfData.nonUniformScale = new Vector3(sdfData.bounds.size.x / minAxis, sdfData.bounds.size.y / minAxis, sdfData.bounds.size.z / minAxis);

            // Create Texture3D and set name to filename of sdfData
            Texture3D newTex = new Texture3D(sdfData.dimensions.x, sdfData.dimensions.y, sdfData.dimensions.z, TextureFormat.RHalf, false);

            newTex.name = System.IO.Path.GetFileNameWithoutExtension(path);

            //TODO improve
            Color[] colorBuffer = new Color[distances.Length];
            for (int i = 0; i < distances.Length; i++)
            {
                //NOTE for compatibility with Visual Effect Graph,
                //the distance must be negative inside surfaces.
                //normalize the distance for better support of scaling bounds
                //Max Distance is always the Magnitude of the baked bound size
                float normalizedDistance = distances[i] / maxDistance;
                colorBuffer[i] = new Color(normalizedDistance, 0f, 0f, 0f);
            }
            newTex.SetPixels(colorBuffer);
            newTex.Apply();


            sdfData.sdfTexture  = newTex;
            sdfData.maxDistance = maxDistance;

            EditorUtility.SetDirty(sdfData);

            //create it
            AssetDatabase.CreateAsset(sdfData, path);
            AssetDatabase.AddObjectToAsset(newTex, sdfData);

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            if (IsPreviewing)
            {
                TogglePreview();
            }
            if (!IsPreviewing)
            {
                TogglePreview();
            }
        }
コード例 #22
0
ファイル: TEXSDFImporter.cs プロジェクト: yansanbai/geospace
        static void OnFinished(TexFontSigned font)
        {
            var sdfPath = TEXPreference.main.MainFolderPath + "/Fonts/TMPro/" + font.id + ".asset";

            TMP_FontAsset asset;

            if (!(asset = AssetDatabase.LoadAssetAtPath <TMP_FontAsset>(sdfPath)))
            {
                // It doesn't exist (or invalid), so create new
                asset = font.asset = ScriptableObject.CreateInstance <TMP_FontAsset>();
                if (!AssetDatabase.IsValidFolder(TEXPreference.main.MainFolderPath + "/Fonts/TMPro"))
                {
                    AssetDatabase.CreateFolder(TEXPreference.main.MainFolderPath + "/Fonts", "TMPro");
                }
                AssetDatabase.CreateAsset(asset, sdfPath);
            }
            asset.fontAssetType = _render >= RenderModes.DistanceField16 ? TMP_FontAsset.FontAssetTypes.SDF : TMP_FontAsset.FontAssetTypes.Bitmap;
            FaceInfo face = GetFaceInfo(_faceInfo, 1);

            asset.AddFaceInfo(face);

            _atlasInfo = new Texture2D(_bufferWidth, _bufferHeight, TextureFormat.Alpha8, false, true);
            var _buffer32 = Array.ConvertAll(_buffers, x => new Color32(x, x, x, x));

            _atlasInfo.SetPixels32(_buffer32);
            _atlasInfo.Apply(false, true);

            // Add GlyphInfo[] to Font Asset
            TMP_Glyph[] glyphs = GetGlyphInfo(_glyphsInfo, 1);
            asset.AddGlyphInfo(glyphs);

            // Get and Add Kerning Pairs to Font Asset

            KerningTable kerningTable = GetKerningTable(font.rawpath, (int)face.PointSize);

            asset.AddKerningInfo(kerningTable);

            // Add Line Breaking Rules
            //LineBreakingTable lineBreakingTable = new LineBreakingTable();
            //

            // Add Font Atlas as Sub-Asset
            asset.atlas          = _atlasInfo;
            _atlasInfo.name      = font.id + " Atlas";
            _atlasInfo.hideFlags = HideFlags.HideInHierarchy;
            AssetDatabase.AddObjectToAsset(_atlasInfo, asset);

            // Create new Material and Add it as Sub-Asset
            Shader   default_Shader = Shader.Find("TextMeshPro/Distance Field"); //m_shaderSelection;
            Material tmp_material   = new Material(default_Shader);

            tmp_material.name = _atlasInfo + " Material";
            tmp_material.SetTexture(ShaderUtilities.ID_MainTex, _atlasInfo);
            tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, _atlasInfo.width);
            tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, _atlasInfo.height);

            tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, asset.normalStyle);
            tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, asset.boldStyle);

            int spread = _render >= RenderModes.DistanceField16 ? _padding + 1 : _padding;

            tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.

            asset.material         = tmp_material;
            tmp_material.hideFlags = HideFlags.HideInHierarchy;

            AssetDatabase.AddObjectToAsset(tmp_material, asset);

            font.asset = asset;
            font.ImportDictionary();
            AssetDatabase.SaveAssets();
        }
コード例 #23
0
        static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            var upgradeLog   = "LWRP Material log:";
            var upgradeCount = 0;

            foreach (var asset in importedAssets)
            {
                if (!asset.ToLowerInvariant().EndsWith(".mat"))
                {
                    continue;
                }

                var material = (Material)AssetDatabase.LoadAssetAtPath(asset, typeof(Material));
                if (!ShaderUtils.IsLWShader(material.shader))
                {
                    continue;
                }

                ShaderPathID id            = ShaderUtils.GetEnumFromPath(material.shader.name);
                var          wasUpgraded   = false;
                var          assetVersions = AssetDatabase.LoadAllAssetsAtPath(asset);
                AssetVersion assetVersion  = null;
                foreach (var subAsset in assetVersions)
                {
                    if (subAsset.GetType() == typeof(AssetVersion))
                    {
                        assetVersion = subAsset as AssetVersion;
                    }
                }
                var debug = "\n" + material.name;

                if (!assetVersion)
                {
                    wasUpgraded  = true;
                    assetVersion = ScriptableObject.CreateInstance <AssetVersion>();
                    if (s_CreatedAssets.Contains(asset))
                    {
                        assetVersion.version = k_Upgraders.Length;
                        s_CreatedAssets.Remove(asset);
                        InitializeLatest(material, id);
                    }
                    else
                    {
                        assetVersion.version = 0;
                    }

                    assetVersion.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector | HideFlags.NotEditable;
                    AssetDatabase.AddObjectToAsset(assetVersion, asset);
                    debug += " initialized.";
                }

                while (assetVersion.version < k_Upgraders.Length)
                {
                    k_Upgraders[assetVersion.version](material, id);
                    debug += $" upgrading:v{assetVersion.version} to v{assetVersion.version + 1}";
                    assetVersion.version++;
                    wasUpgraded = true;
                }

                if (wasUpgraded)
                {
                    upgradeLog += debug;
                    upgradeCount++;
                    EditorUtility.SetDirty(assetVersion);
                }
            }
            if (upgradeCount > 0)
            {
                Debug.Log(upgradeLog);
            }
        }
コード例 #24
0
 public void AddObjectToAsset(string path)
 {
     AssetDatabase.AddObjectToAsset(this, path);
     AssetDatabase.ImportAsset(path);
 }
コード例 #25
0
        static public void UpdateCache()
        {
            // Deserialize the cache from the unity resources
            if (eventCache == null)
            {
                eventCache = AssetDatabase.LoadAssetAtPath(CacheAssetFullName, typeof(EventCache)) as EventCache;
                if (eventCache == null || eventCache.cacheVersion != EventCache.CurrentCacheVersion)
                {
                    UnityEngine.Debug.Log("FMOD Studio: Cannot find serialized event cache or cache in old format, creating new instance");
                    eventCache = ScriptableObject.CreateInstance <EventCache>();
                    eventCache.cacheVersion = EventCache.CurrentCacheVersion;

                    AssetDatabase.CreateAsset(eventCache, CacheAssetFullName);
                }
            }

            if (EditorUtils.GetBankDirectory() == null)
            {
                ClearCache();
                return;
            }

            string defaultBankFolder = null;

            if (!Settings.Instance.HasPlatforms)
            {
                defaultBankFolder = EditorUtils.GetBankDirectory();
            }
            else
            {
                FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                if (platform == FMODPlatform.None)
                {
                    platform = FMODPlatform.PlayInEditor;
                }

                defaultBankFolder = Path.Combine(EditorUtils.GetBankDirectory(), Settings.Instance.GetBankPlatform(platform));
            }

            string[] bankPlatforms = EditorUtils.GetBankPlatforms();
            string[] bankFolders   = new string[bankPlatforms.Length];
            for (int i = 0; i < bankPlatforms.Length; i++)
            {
                bankFolders[i] = Path.Combine(EditorUtils.GetBankDirectory(), bankPlatforms[i]);
            }

            List <String> stringBanks = new List <string>(0);

            try
            {
                var files = Directory.GetFiles(defaultBankFolder, "*." + StringBankExtension);
                stringBanks = new List <string>(files);
            }
            catch
            {
            }

            // Strip out OSX resource-fork files that appear on FAT32
            stringBanks.RemoveAll((x) => Path.GetFileName(x).StartsWith("._"));

            if (stringBanks.Count == 0)
            {
                bool wasValid = eventCache.StringsBankWriteTime != DateTime.MinValue;
                ClearCache();
                if (wasValid)
                {
                    UnityEngine.Debug.LogError(String.Format("FMOD Studio: Directory {0} doesn't contain any banks. Build from the tool or check the path in the settings", defaultBankFolder));
                }
                return;
            }

            // If we have multiple .strings.bank files find the most recent
            stringBanks.Sort((a, b) => File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)));
            string stringBankPath = stringBanks[0];

            // Use the string bank timestamp as a marker for the most recent build of any bank because it gets exported every time
            if (File.GetLastWriteTime(stringBankPath) == eventCache.StringsBankWriteTime)
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            if (EditorUtils.IsFileOpenByStudio(stringBankPath))
            {
                countdownTimer = CountdownTimerReset;
                return;
            }


            FMOD.Studio.Bank stringBank;
            EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));
            if (!stringBank.isValid())
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            // Iterate every string in the strings bank and look for any that identify banks
            int stringCount;

            stringBank.getStringCount(out stringCount);
            List <string> bankFileNames = new List <string>();

            for (int stringIndex = 0; stringIndex < stringCount; stringIndex++)
            {
                string currentString;
                Guid   currentGuid;
                stringBank.getStringInfo(stringIndex, out currentGuid, out currentString);
                const string BankPrefix       = "bank:/";
                int          BankPrefixLength = BankPrefix.Length;
                if (currentString.StartsWith(BankPrefix))
                {
                    string bankFileName = currentString.Substring(BankPrefixLength) + "." + BankExtension;
                    if (!bankFileName.Contains(StringBankExtension)) // filter out the strings bank
                    {
                        bankFileNames.Add(bankFileName);
                    }
                }
            }

            // Unload the strings bank
            stringBank.unload();

            // Check if any of the files are still being written by studio
            foreach (string bankFileName in bankFileNames)
            {
                string bankPath = Path.Combine(defaultBankFolder, bankFileName);

                if (!File.Exists(bankPath))
                {
                    // TODO: this is meant to catch the case where we're in the middle of a build and a bank is being built
                    // for the first time. But it also stops someone trying to import an incomplete set of banks without any error message.
                    countdownTimer = CountdownTimerReset;
                    return;
                }

                EditorBankRef bankRef = eventCache.EditorBanks.Find((x) => bankPath == x.Path);
                if (bankRef == null)
                {
                    if (EditorUtils.IsFileOpenByStudio(bankPath))
                    {
                        countdownTimer = CountdownTimerReset;
                        return;
                    }
                    continue;
                }

                if (bankRef.LastModified != File.GetLastWriteTime(bankPath))
                {
                    if (EditorUtils.IsFileOpenByStudio(bankPath))
                    {
                        countdownTimer = CountdownTimerReset;
                        return;
                    }
                }
            }

            // Count down the timer in case we catch studio in-between updating two files.
            if (countdownTimer-- > 0)
            {
                return;
            }

            // All files are finished being modified by studio so update the cache

            // Stop editor preview so no stale data being held
            EditorUtils.PreviewStop();

            // Reload the strings bank
            EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));
            if (!stringBank.isValid())
            {
                ClearCache();
                return;
            }
            FileInfo stringBankFileInfo = new FileInfo(stringBankPath);

            eventCache.StringsBankWriteTime = stringBankFileInfo.LastWriteTime;
            string masterBankFileName = Path.GetFileName(stringBankPath).Replace(StringBankExtension, BankExtension);

            AssetDatabase.StartAssetEditing();

            if (eventCache.StringsBankRef == null)
            {
                eventCache.StringsBankRef           = ScriptableObject.CreateInstance <EditorBankRef>();
                eventCache.StringsBankRef.FileSizes = new List <EditorBankRef.NameValuePair>();
                eventCache.EditorBanks.Add(eventCache.StringsBankRef);
                AssetDatabase.AddObjectToAsset(eventCache.StringsBankRef, eventCache);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(eventCache.StringsBankRef));
            }
            eventCache.StringsBankRef.Path         = stringBankPath;
            eventCache.StringsBankRef.LastModified = eventCache.StringsBankWriteTime;
            eventCache.StringsBankRef.FileSizes.Clear();
            if (Settings.Instance.HasPlatforms)
            {
                for (int i = 0; i < bankPlatforms.Length; i++)
                {
                    eventCache.StringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], stringBankFileInfo.Length));
                }
            }
            else
            {
                eventCache.StringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", stringBankFileInfo.Length));
            }

            eventCache.EditorBanks.ForEach((x) => x.Exists = false);
            eventCache.StringsBankRef.Exists = true;

            string[] folderContents = Directory.GetFiles(defaultBankFolder);

            foreach (string bankFileName in bankFileNames)
            {
                // Get the true file path, can't trust the character case we got from the string bank
                string bankPath = ArrayUtility.Find(folderContents, x => (string.Equals(bankFileName, Path.GetFileName(x), StringComparison.CurrentCultureIgnoreCase)));

                FileInfo      bankFileInfo = new FileInfo(bankPath);
                EditorBankRef bankRef      = eventCache.EditorBanks.Find((x) => bankFileInfo.FullName == x.Path);

                // New bank we've never seen before
                if (bankRef == null)
                {
                    bankRef = ScriptableObject.CreateInstance <EditorBankRef>();
                    AssetDatabase.AddObjectToAsset(bankRef, eventCache);
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(bankRef));
                    bankRef.Path         = bankFileInfo.FullName;
                    bankRef.LastModified = DateTime.MinValue;
                    bankRef.FileSizes    = new List <EditorBankRef.NameValuePair>();
                    eventCache.EditorBanks.Add(bankRef);
                }

                bankRef.Exists = true;

                // Timestamp check - if it doesn't match update events from that bank
                if (bankRef.LastModified != bankFileInfo.LastWriteTime)
                {
                    bankRef.LastModified = bankFileInfo.LastWriteTime;
                    UpdateCacheBank(bankRef);
                }

                // Update file sizes
                bankRef.FileSizes.Clear();
                if (Settings.Instance.HasPlatforms)
                {
                    for (int i = 0; i < bankPlatforms.Length; i++)
                    {
                        string platformBankPath = Path.Combine(bankFolders[i], bankFileName);
                        var    fileInfo         = new FileInfo(platformBankPath);
                        if (fileInfo.Exists)
                        {
                            bankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], fileInfo.Length));
                        }
                    }
                }
                else
                {
                    string platformBankPath = Path.Combine(EditorUtils.GetBankDirectory(), bankFileName);
                    var    fileInfo         = new FileInfo(platformBankPath);
                    if (fileInfo.Exists)
                    {
                        bankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", fileInfo.Length));
                    }
                }

                if (bankFileInfo.Name == masterBankFileName)
                {
                    eventCache.MasterBankRef = bankRef;
                }
            }


            // Unload the strings bank
            stringBank.unload();

            // Remove any stale entries from bank and event lists
            eventCache.EditorBanks.FindAll((x) => !x.Exists).ForEach(RemoveCacheBank);
            eventCache.EditorBanks.RemoveAll((x) => !x.Exists);
            eventCache.EditorEvents.RemoveAll((x) => x.Banks.Count == 0);

            OnCacheChange();
            AssetDatabase.StopAssetEditing();
        }
コード例 #26
0
        public static void SyncAssetObjects(ActionListAsset actionListAsset)
        {
            bool modified = false;

            // Search for assets to delete
            Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(actionListAsset));
            foreach (Object asset in assets)
            {
                Action actionAsset = asset as Action;
                if (actionAsset != null)
                {
                    bool foundMatch = false;

                    foreach (Action action in actionListAsset.actions)
                    {
                        if (actionAsset == action)
                        {
                            foundMatch = true;
                            break;
                        }
                    }

                    if (!foundMatch)
                    {
                        //Debug.LogWarning ("Found no match of asset " + actionAsset + " - deleting now");
                        Undo.DestroyObjectImmediate(actionAsset);
                        modified = true;
                    }
                }
            }

            // Search for assets to add
            foreach (Action action in actionListAsset.actions)
            {
                if (action != null)
                {
                    bool foundMatch = false;

                    foreach (Object asset in assets)
                    {
                        Action actionAsset = asset as Action;
                        if (actionAsset == action)
                        {
                            foundMatch = true;
                            break;
                        }
                    }

                    if (!foundMatch)
                    {
                        action.hideFlags = HideFlags.HideInHierarchy;
                        AssetDatabase.AddObjectToAsset(action, actionListAsset);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(action));
                        //Debug.LogWarning ("Found no match of " + action + " '" + action.name + "' in database - adding now to " + AssetDatabase.GetAssetPath (action));
                        modified = true;
                    }
                }
            }

            if (modified)
            {
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }
コード例 #27
0
        static public void UpdateCache()
        {
            // Deserialize the cache from the unity resources
            if (eventCache == null)
            {
                eventCache = AssetDatabase.LoadAssetAtPath(CacheAssetFullName, typeof(EventCache)) as EventCache;
                if (eventCache == null || eventCache.cacheVersion != EventCache.CurrentCacheVersion)
                {
                    UnityEngine.Debug.Log("FMOD Studio: Cannot find serialized event cache or cache in old format, creating new instance");
                    eventCache = ScriptableObject.CreateInstance <EventCache>();
                    eventCache.cacheVersion = EventCache.CurrentCacheVersion;
                    if (!Directory.Exists("Assets/Plugins/FMOD/Resources"))
                    {
                        AssetDatabase.CreateFolder("Assets/Plugins/FMOD", "Resources");
                    }
                    AssetDatabase.CreateAsset(eventCache, CacheAssetFullName);
                }
            }

            var settings = Settings.Instance;

            if (string.IsNullOrEmpty(settings.SourceBankPath))
            {
                ClearCache();
                return;
            }

            string defaultBankFolder = null;

            if (!Settings.Instance.HasPlatforms)
            {
                defaultBankFolder = settings.SourceBankPath;
            }
            else
            {
                FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                if (platform == FMODPlatform.None)
                {
                    platform = FMODPlatform.PlayInEditor;
                }

                defaultBankFolder = RuntimeUtils.GetCommonPlatformPath(Path.Combine(settings.SourceBankPath, Settings.Instance.GetBankPlatform(platform)));
            }

            string[] bankPlatforms = EditorUtils.GetBankPlatforms();
            string[] bankFolders   = new string[bankPlatforms.Length];
            for (int i = 0; i < bankPlatforms.Length; i++)
            {
                bankFolders[i] = RuntimeUtils.GetCommonPlatformPath(Path.Combine(settings.SourceBankPath, bankPlatforms[i]));
            }

            List <string> stringBanks = new List <string>(0);

            try
            {
                var files = Directory.GetFiles(defaultBankFolder, "*." + StringBankExtension, SearchOption.AllDirectories);
                stringBanks = new List <string>(files);
            }
            catch
            {
            }

            // Strip out OSX resource-fork files that appear on FAT32
            stringBanks.RemoveAll((x) => Path.GetFileName(x).StartsWith("._"));

            if (stringBanks.Count == 0)
            {
                bool wasValid = eventCache.StringsBankWriteTime != DateTime.MinValue;
                ClearCache();
                if (wasValid)
                {
                    UnityEngine.Debug.LogError(string.Format("FMOD Studio: Directory {0} doesn't contain any banks. Build from the tool or check the path in the settings", defaultBankFolder));
                }
                return;
            }

            // If we have multiple .strings.bank files find the most recent
            stringBanks.Sort((a, b) => File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)));

            // Use the most recent string bank timestamp as a marker for the most recent build of any bank because it gets exported every time
            DateTime lastWriteTime = File.GetLastWriteTime(stringBanks[0]);

            if (lastWriteTime == eventCache.StringsBankWriteTime)
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            if (EditorUtils.IsFileOpenByStudio(stringBanks[0]))
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            // Most recent strings bank is newer than last cache update time, recache.

            // Get a list of all banks
            List <string>  bankFileNames          = new List <string>();
            List <string>  reducedStringBanksList = new List <string>();
            HashSet <Guid> stringBankGuids        = new HashSet <Guid>();

            foreach (string stringBankPath in stringBanks)
            {
                FMOD.Studio.Bank stringBank;
                EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));

                if (!stringBank.isValid())
                {
                    countdownTimer = CountdownTimerReset;
                    return;
                }
                else
                {
                    // Unload the strings bank
                    stringBank.unload();
                }
                Guid stringBankGuid;
                EditorUtils.CheckResult(stringBank.getID(out stringBankGuid));

                if (!stringBankGuids.Add(stringBankGuid))
                {
                    // If we encounter multiple string banks with the same GUID then only use the first. This handles the scenario where
                    // a Studio project is cloned and extended for DLC with a new master bank name.
                    continue;
                }

                reducedStringBanksList.Add(stringBankPath);
            }

            bankFileNames = new List <string>(Directory.GetFiles(defaultBankFolder, "*.bank", SearchOption.AllDirectories));
            bankFileNames.RemoveAll(x => x.Contains(".strings"));

            stringBanks = reducedStringBanksList;

            if (!UnityEditorInternal.InternalEditorUtility.inBatchMode)
            {
                // Check if any of the files are still being written by studio
                foreach (string bankFileName in bankFileNames)
                {
                    EditorBankRef bankRef = eventCache.EditorBanks.Find((x) => RuntimeUtils.GetCommonPlatformPath(bankFileName) == x.Path);
                    if (bankRef == null)
                    {
                        if (EditorUtils.IsFileOpenByStudio(bankFileName))
                        {
                            countdownTimer = CountdownTimerReset;
                            return;
                        }
                        continue;
                    }

                    if (bankRef.LastModified != File.GetLastWriteTime(bankFileName))
                    {
                        if (EditorUtils.IsFileOpenByStudio(bankFileName))
                        {
                            countdownTimer = CountdownTimerReset;
                            return;
                        }
                    }
                }

                // Count down the timer in case we catch studio in-between updating two files.
                if (countdownTimer-- > 0)
                {
                    return;
                }
            }

            eventCache.StringsBankWriteTime = lastWriteTime;

            // All files are finished being modified by studio so update the cache

            // Stop editor preview so no stale data being held
            EditorUtils.PreviewStop();

            // Reload the strings banks
            List <FMOD.Studio.Bank> loadedStringsBanks = new List <FMOD.Studio.Bank>();

            try
            {
                AssetDatabase.StartAssetEditing();

                eventCache.EditorBanks.ForEach((x) => x.Exists = false);
                HashSet <string> masterBankFileNames = new HashSet <string>();

                foreach (string stringBankPath in stringBanks)
                {
                    FMOD.Studio.Bank stringBank;
                    EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));

                    if (!stringBank.isValid())
                    {
                        ClearCache();
                        return;
                    }

                    loadedStringsBanks.Add(stringBank);

                    FileInfo stringBankFileInfo = new FileInfo(stringBankPath);

                    string masterBankFileName = Path.GetFileName(stringBankPath).Replace(StringBankExtension, BankExtension);
                    masterBankFileNames.Add(masterBankFileName);

                    EditorBankRef stringsBankRef = eventCache.StringsBanks.Find(x => RuntimeUtils.GetCommonPlatformPath(stringBankPath) == x.Path);

                    if (stringsBankRef == null)
                    {
                        stringsBankRef           = ScriptableObject.CreateInstance <EditorBankRef>();
                        stringsBankRef.FileSizes = new List <EditorBankRef.NameValuePair>();
                        AssetDatabase.AddObjectToAsset(stringsBankRef, eventCache);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(stringsBankRef));
                        eventCache.EditorBanks.Add(stringsBankRef);
                        eventCache.StringsBanks.Add(stringsBankRef);
                    }

                    stringsBankRef.Path         = RuntimeUtils.GetCommonPlatformPath(stringBankPath);
                    stringsBankRef.name         = "bank:/" + Path.GetFileName(stringsBankRef.Path);
                    stringsBankRef.LastModified = stringBankFileInfo.LastWriteTime;
                    stringsBankRef.Exists       = true;
                    stringsBankRef.FileSizes.Clear();

                    if (Settings.Instance.HasPlatforms)
                    {
                        for (int i = 0; i < bankPlatforms.Length; i++)
                        {
                            stringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], stringBankFileInfo.Length));
                        }
                    }
                    else
                    {
                        stringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", stringBankFileInfo.Length));
                    }
                }

                eventCache.EditorParameters.ForEach((x) => x.Exists = false);
                foreach (string bankFileName in bankFileNames)
                {
                    FileInfo      bankFileInfo = new FileInfo(bankFileName);
                    EditorBankRef bankRef      = eventCache.EditorBanks.Find((x) => RuntimeUtils.GetCommonPlatformPath(bankFileInfo.FullName) == x.Path);

                    // New bank we've never seen before
                    if (bankRef == null)
                    {
                        bankRef = ScriptableObject.CreateInstance <EditorBankRef>();
                        AssetDatabase.AddObjectToAsset(bankRef, eventCache);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(bankRef));
                        bankRef.Path         = RuntimeUtils.GetCommonPlatformPath(bankFileName);
                        bankRef.name         = "bank:/" + Path.GetFileName(bankRef.Path);
                        bankRef.LastModified = DateTime.MinValue;
                        bankRef.FileSizes    = new List <EditorBankRef.NameValuePair>();
                        eventCache.EditorBanks.Add(bankRef);
                    }

                    bankRef.Exists = true;

                    // Timestamp check - if it doesn't match update events from that bank
                    if (bankRef.LastModified != bankFileInfo.LastWriteTime)
                    {
                        bankRef.LastModified = bankFileInfo.LastWriteTime;
                        UpdateCacheBank(bankRef);
                    }

                    // Update file sizes
                    bankRef.FileSizes.Clear();
                    if (Settings.Instance.HasPlatforms)
                    {
                        for (int i = 0; i < bankPlatforms.Length; i++)
                        {
                            string platformBankPath = RuntimeUtils.GetCommonPlatformPath(Path.Combine(bankFolders[i], bankFileName));
                            var    fileInfo         = new FileInfo(platformBankPath);
                            if (fileInfo.Exists)
                            {
                                bankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], fileInfo.Length));
                            }
                        }
                    }
                    else
                    {
                        string platformBankPath = RuntimeUtils.GetCommonPlatformPath(Path.Combine(Settings.Instance.SourceBankPath, bankFileName));
                        var    fileInfo         = new FileInfo(platformBankPath);
                        if (fileInfo.Exists)
                        {
                            bankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", fileInfo.Length));
                        }
                    }

                    if (masterBankFileNames.Contains(bankFileInfo.Name))
                    {
                        if (!eventCache.MasterBanks.Exists(x => RuntimeUtils.GetCommonPlatformPath(bankFileInfo.FullName) == x.Path))
                        {
                            eventCache.MasterBanks.Add(bankRef);
                        }
                    }
                }

                // Remove any stale entries from bank, event and parameter lists
                eventCache.EditorBanks.FindAll((x) => !x.Exists).ForEach(RemoveCacheBank);
                eventCache.EditorBanks.RemoveAll((x) => !x.Exists);
                eventCache.EditorEvents.RemoveAll((x) => x.Banks.Count == 0);
                eventCache.EditorParameters.RemoveAll((x) => !x.Exists);
                eventCache.MasterBanks.RemoveAll((x) => !x.Exists);
                eventCache.StringsBanks.RemoveAll((x) => !x.Exists);
            }
            finally
            {
                // Unload the strings banks
                loadedStringsBanks.ForEach(x => x.unload());
                AssetDatabase.StopAssetEditing();
            }
        }
コード例 #28
0
    void Inherit()
    {
        string inheritedClass     = "";
        bool   isAlreadyInherited = false;

        foreach (Node node in target.nodes)
        {
            if (node is InheritTargetNode t)
            {
                isAlreadyInherited = true;
                inheritedClass     = t.target;
                break;
            }
        }
        if (!isAlreadyInherited)
        {
            InheritTargetNode t = target.AddNode <InheritTargetNode>() as InheritTargetNode;
            t.name        = "Inherit Target";
            t.target      = inheritGraph.name;
            t.IsDeletable = false;
            AssetDatabase.AddObjectToAsset(t, target);
            List <Node> createdNonSubNodes = new List <Node>();
            Dictionary <string, List <string> > outputPorts = new Dictionary <string, List <string> >();
            foreach (Node _node in inheritGraph.nodes)
            {
                if (_node == null)
                {
                    continue;
                }
                if (_node is SubNode sub)
                {
                    SubNode node = target.AddNode(_node.GetType()) as SubNode;
                    node.OnCreated();
                    node.name        = inherited_prefix + _node.name;
                    node.nodeName    = sub.nodeName;
                    node.isInherited = true;
                    node.InheritFrom(_node);
                    node.position = _node.position;
                    AssetDatabase.AddObjectToAsset(node, target);
                }
                else if (_node is ITreeGraphNode i)
                {
                    Node newNode = target.AddNode(_node.GetType());
                    newNode.OnCreated();

                    if (newNode is ITreeGraphNode new_i)
                    {
                        new_i.SetNodeName(i.GetNodeName());
                        new_i.InheritFrom(_node);
                    }

                    newNode.name     = _node.name;
                    newNode.position = _node.position;
                    AssetDatabase.AddObjectToAsset(newNode, target);

                    string nodeName = i.GetNodeName();
                    if (!createdNonSubNodes.Contains(newNode))
                    {
                        createdNonSubNodes.Add(newNode);
                        if (!outputPorts.ContainsKey(nodeName))
                        {
                            outputPorts[nodeName] = new List <string>();
                            var outputs = _node.GetOutputPort("output").GetConnections();
                            foreach (var output in outputs)
                            {
                                if (output.node is ITreeGraphNode ibt_output)
                                {
                                    if (!outputPorts[nodeName].Contains(ibt_output.GetNodeName()))
                                    {
                                        outputPorts[nodeName].Add(ibt_output.GetNodeName());
                                    }
                                }
                            }
                        }
                    }
                }
            }


            foreach (Node parent in createdNonSubNodes)
            {
                ITreeGraphNode ibt_parent = parent as ITreeGraphNode;
                if (outputPorts.ContainsKey(ibt_parent.GetNodeName()))
                {
                    foreach (string outputTarget in outputPorts[ibt_parent.GetNodeName()])
                    {
                        Node child = null;
                        foreach (Node _child in createdNonSubNodes)
                        {
                            ITreeGraphNode ibt_target = _child as ITreeGraphNode;
                            if (ibt_target.GetNodeName() == outputTarget)
                            {
                                child = _child;
                                break;
                            }
                        }

                        if (child != null)
                        {
                            parent.GetOutputPort("output").Connect(child.GetInputPort("input"));
                        }
                    }
                }
            }

            if (NodeEditorPreferences.GetSettings().autoSave)
            {
                AssetDatabase.SaveAssets();
            }
            NodeEditorWindow.RepaintAll();
        }
        else
        {
            Debug.LogError("This graph has already inherited \"" + inheritedClass + "\".");
        }
    }
コード例 #29
0
        /// <summary>
        /// Draws the ItemTypeManager.
        /// </summary>
        public override void OnGUI()
        {
            var toolbarSelection = GUILayout.Toolbar(m_DrawItemType ? 0 : 1, m_ToolbarStrings, EditorStyles.toolbarButton);

            m_DrawItemType = toolbarSelection == 0;
            GUILayout.Space(10);

            if (m_DrawItemType)
            {
                GUILayout.Label("Item Types", Shared.Editor.Inspectors.Utility.InspectorStyles.CenterBoldLabel);
            }
            else
            {
                GUILayout.Label("Categories", Shared.Editor.Inspectors.Utility.InspectorStyles.CenterBoldLabel);
            }

            EditorGUILayout.BeginHorizontal();
            var itemCollection = EditorGUILayout.ObjectField("Item Collection", m_ItemCollection, typeof(ItemCollection), false) as ItemCollection;

            if (GUILayout.Button("Create", GUILayout.MaxWidth(100)))
            {
                var path = EditorUtility.SaveFilePanel("Save Item Collection", "Assets", "ItemCollection.asset", "asset");
                if (path.Length != 0 && Application.dataPath.Length < path.Length)
                {
                    itemCollection = ScriptableObject.CreateInstance <ItemCollection>();
                    var category = ScriptableObject.CreateInstance <Category>();
                    category.ID               = Category.GenerateID();
                    category.name             = "Items";
                    itemCollection.Categories = new Category[] { category };

                    // Save the collection.
                    path = string.Format("Assets/{0}", path.Substring(Application.dataPath.Length + 1));
                    AssetDatabase.DeleteAsset(path);
                    AssetDatabase.CreateAsset(itemCollection, path);
                    AssetDatabase.AddObjectToAsset(category, path);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.ImportAsset(path);
                }
            }
            EditorGUILayout.EndHorizontal();

            if (itemCollection != m_ItemCollection)
            {
                m_ItemCollection = itemCollection;
                if (m_ItemCollection != null)
                {
                    EditorPrefs.SetString(ManagerUtility.LastItemCollectionGUIDString, AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(itemCollection)));
                    (m_CategoryTreeView.TreeModal as CategoryCollectionModal).ItemCollection = m_ItemCollection;
                    (m_ItemTypeTreeView.TreeModal as ItemTypeCollectionModal).ItemCollection = m_ItemCollection;
                }
                else
                {
                    EditorPrefs.SetString(ManagerUtility.LastItemCollectionGUIDString, string.Empty);
                    (m_CategoryTreeView.TreeModal as CategoryCollectionModal).ItemCollection = null;
                    (m_ItemTypeTreeView.TreeModal as ItemTypeCollectionModal).ItemCollection = null;
                }
                m_CategoryTreeView.Reload();
                m_ItemTypeTreeView.Reload();
            }

            // ItemCollection must be populated in order to create Categories/ItemTypes.
            if (m_ItemCollection == null)
            {
                EditorGUILayout.HelpBox("An ItemCollection must be selected. Use the \"Create\" button to create a new collection.", MessageType.Error);
                return;
            }

            if (m_DrawItemType)
            {
                DrawItemTypes();
            }
            else
            {
                DrawCategories();
            }
        }
コード例 #30
0
ファイル: XRSettingsManager.cs プロジェクト: hassi00/ARmeisi
        private void DisplayLoaderSelectionUI()
        {
            if (!m_HasCompletedRequest)
            {
                return;
            }

            if (!m_HasKNownLocalLoaders)
            {
                if (!m_XRPackages.Any())
                {
                    EditorGUILayout.HelpBox(Content.k_ProvidersUnavailable, MessageType.Error);
                    return;
                }

                if (!m_HasInstalledProviders)
                {
                    EditorGUILayout.HelpBox(Content.k_NeedToInstallAProvider, MessageType.Warning);
                    return;
                }
            }

            BuildTargetGroup buildTargetGroup   = EditorGUILayout.BeginBuildTargetSelectionGrouping();
            bool             buildTargetChanged = m_LastBuildTargetGroup != buildTargetGroup;

            if (buildTargetChanged)
            {
                m_LastBuildTargetGroup = buildTargetGroup;
            }

            XRGeneralSettings settings = currentSettings.SettingsForBuildTarget(buildTargetGroup);

            if (settings == null)
            {
                settings = ScriptableObject.CreateInstance <XRGeneralSettings>() as XRGeneralSettings;
                currentSettings.SetSettingsForBuildTarget(buildTargetGroup, settings);
                settings.name = $"{buildTargetGroup.ToString()} Settings";
                AssetDatabase.AddObjectToAsset(settings, AssetDatabase.GetAssetOrScenePath(currentSettings));
            }

            var serializedSettingsObject = new SerializedObject(settings);

            serializedSettingsObject.Update();

            SerializedProperty initOnStart = serializedSettingsObject.FindProperty("m_InitManagerOnStart");

            EditorGUILayout.PropertyField(initOnStart, Content.s_LoaderInitOnStartLabel);

            SerializedProperty loaderProp = serializedSettingsObject.FindProperty("m_LoaderManagerInstance");

            if (!CachedSettingsEditor.ContainsKey(buildTargetGroup))
            {
                CachedSettingsEditor.Add(buildTargetGroup, null);
            }

            if (loaderProp.objectReferenceValue == null)
            {
                var xrManagerSettings = ScriptableObject.CreateInstance <XRManagerSettings>() as XRManagerSettings;
                xrManagerSettings.name = $"{buildTargetGroup.ToString()} Providers";
                AssetDatabase.AddObjectToAsset(xrManagerSettings, AssetDatabase.GetAssetOrScenePath(currentSettings));
                loaderProp.objectReferenceValue = xrManagerSettings;
                serializedSettingsObject.ApplyModifiedProperties();
            }

            var obj = loaderProp.objectReferenceValue;

            if (obj != null)
            {
                loaderProp.objectReferenceValue = obj;

                if (CachedSettingsEditor[buildTargetGroup] == null)
                {
                    CachedSettingsEditor[buildTargetGroup] = Editor.CreateEditor(obj) as XRManagerSettingsEditor;

                    if (CachedSettingsEditor[buildTargetGroup] == null)
                    {
                        Debug.LogError("Failed to create a view for XR Manager Settings Instance");
                    }
                }

                if (CachedSettingsEditor[buildTargetGroup] != null)
                {
                    if (buildTargetChanged)
                    {
                        CachedSettingsEditor[buildTargetGroup].BuildTarget = buildTargetGroup;
                        CachedSettingsEditor[buildTargetGroup].Reload();
                    }
                    CachedSettingsEditor[buildTargetGroup].OnInspectorGUI();
                }
            }
            else if (obj == null)
            {
                settings.AssignedSettings       = null;
                loaderProp.objectReferenceValue = null;
            }

            EditorGUILayout.EndBuildTargetSelectionGrouping();

            serializedSettingsObject.ApplyModifiedProperties();
        }