public static SettingsProvider XI18NSetting()
        {
            return(new SettingsProvider(I18NEditorConst.ProjectSetting_Node, SettingsScope.Project, new string[] { "Nekonya", "TinaX", "I18N", "TinaX.I18N", "Localization" })
            {
                label = "X I18N",
                guiHandler = (searchContent) =>
                {
                    if (!mDataRefreshed)
                    {
                        refreshData();
                    }
                    EditorGUILayout.BeginVertical(Styles.body);
                    if (mConfig == null)
                    {
                        GUILayout.Space(20);
                        GUILayout.Label(I18Ns.NoConfig);
                        if (GUILayout.Button(I18Ns.BtnCreateConfigFile, Styles.style_btn_normal, GUILayout.MaxWidth(120)))
                        {
                            mConfig = XConfig.CreateConfigIfNotExists <I18NConfig>(I18NConst.ConfigPath_Resources, AssetLoadType.Resources);
                            refreshData();
                        }
                    }
                    else
                    {
                        if (mList_Regions == null)
                        {
                            mList_Regions = new ReorderableList(mConfig_SerObj,
                                                                mConfig_SerObj.FindProperty("Regions"),
                                                                true,  //draggable
                                                                true,  //display head
                                                                true,  //add button
                                                                true); //remove button
                            mList_Regions.drawElementCallback = (rect, index, isActive, isFocused) =>
                            {
                                rect.y += 2;
                                rect.height = EditorGUIUtility.singleLineHeight;
                                var singleLine = EditorGUIUtility.singleLineHeight + 2;
                                float base_line = 0;

                                SerializedProperty itemData = mList_Regions.serializedProperty.GetArrayElementAtIndex(index);
                                SerializedProperty item_name = itemData.FindPropertyRelative("Name");
                                SerializedProperty item_bind_language = itemData.FindPropertyRelative("BindLanguage");
                                SerializedProperty item_json_dict = itemData.FindPropertyRelative("JsonDicts");
                                SerializedProperty item_asset_dict = itemData.FindPropertyRelative("AssetDicts");

                                //line 1  region name;
                                var rect_regionName = rect;
                                rect_regionName.width = 320;
                                EditorGUI.PropertyField(rect_regionName, item_name, new GUIContent(I18Ns.RegionName));
                                base_line += 1;

                                //line 2 Bind Language
                                var rect_language_title = rect;
                                rect_language_title.y += singleLine;
                                rect_language_title.width = 125;
                                EditorGUI.LabelField(rect_language_title, new GUIContent(I18Ns.BindLanaguage, I18Ns.BindLanaguage_Tip));

                                if (item_bind_language.arraySize > 0)
                                {
                                    for (var i = 0; i < item_bind_language.arraySize; i++)
                                    {
                                        var _rect = rect;
                                        _rect.y += singleLine * (i + 1);
                                        _rect.x += 130;

                                        var _rect_content = _rect;
                                        _rect_content.width = 180;

                                        SerializedProperty item_language = item_bind_language.GetArrayElementAtIndex(i);
                                        EditorGUI.PropertyField(_rect_content, item_language, GUIContent.none);

                                        var _rect_del_btn = _rect;
                                        _rect_del_btn.width = 25;
                                        _rect_del_btn.x += _rect_content.width + 5;
                                        if (GUI.Button(_rect_del_btn, new GUIContent("×", "delete")))
                                        {
                                            item_bind_language.DeleteArrayElementAtIndex(i);
                                        }
                                    }
                                }

                                var rect_language_add_btn = rect;
                                rect_language_add_btn.y += singleLine * (item_bind_language.arraySize + 1);
                                rect_language_add_btn.x += 130;
                                rect_language_add_btn.width = 110;
                                if (GUI.Button(rect_language_add_btn, "Add Language"))
                                {
                                    int _index = item_bind_language.arraySize;
                                    item_bind_language.InsertArrayElementAtIndex(_index);
                                    var _item = item_bind_language.GetArrayElementAtIndex(_index);
                                    _item.enumValueIndex = 0;
                                }
                                base_line += item_bind_language.arraySize + 1.5f;

                                //line 3 Json Dicts
                                var rect_json_dict_title = rect;
                                rect_json_dict_title.y += (base_line) * singleLine;
                                rect_json_dict_title.width = 125;
                                EditorGUI.LabelField(rect_json_dict_title, new GUIContent(I18Ns.JsonDict));

                                if (item_json_dict.arraySize > 0)
                                {
                                    var _json_base_dict = rect;
                                    _json_base_dict.y += base_line * singleLine;
                                    for (var i = 0; i < item_json_dict.arraySize; i++)
                                    {
                                        var _rect = _json_base_dict;
                                        _rect.y += (singleLine * 3.5f) * i;
                                        _rect.x += 130;
                                        _rect.width -= 130;

                                        SerializedProperty _item_data = item_json_dict.GetArrayElementAtIndex(i);
                                        SerializedProperty _item_loadPath = _item_data.FindPropertyRelative("LoadPath");
                                        SerializedProperty _item_editorloadPath = _item_data.FindPropertyRelative("EditorLoadPath");
                                        SerializedProperty _item_groupname = _item_data.FindPropertyRelative("GroupName");
                                        SerializedProperty _item_base64 = _item_data.FindPropertyRelative("Base64Value");

                                        //line 1: load path
                                        var _rect_load_path = _rect;
                                        _rect_load_path.width -= 30;
                                        EditorGUI.PropertyField(_rect_load_path, _item_loadPath, new GUIContent(I18Ns.JsonLoadPath, I18Ns.JsonLoadPath_Tips));
                                        //line 2: editor load path;
                                        var _rect_editor_load_path = _rect;
                                        _rect_editor_load_path.y += singleLine;
                                        _rect_editor_load_path.width -= 30;
                                        _rect_editor_load_path.width -= 55;
                                        EditorGUI.PropertyField(_rect_editor_load_path, _item_editorloadPath, new GUIContent(I18Ns.EditorJsonLoadPath, I18Ns.EditorJsonLoadPath_Tips));
                                        var _rect_editor_load_path_btn = _rect;
                                        _rect_editor_load_path_btn.y += singleLine;
                                        _rect_editor_load_path_btn.width = 50;
                                        _rect_editor_load_path_btn.x += _rect_editor_load_path.width + 5;
                                        if (GUI.Button(_rect_editor_load_path_btn, "Select"))
                                        {
                                            var path = EditorUtility.OpenFilePanel("Select Lua Entry File", "Assets/", "");
                                            if (!path.IsNullOrEmpty())
                                            {
                                                var root_path = Directory.GetCurrentDirectory().Replace("\\", "/");
                                                if (path.StartsWith(root_path))
                                                {
                                                    path = path.Substring(root_path.Length + 1, path.Length - root_path.Length - 1);
                                                    path = path.Replace("\\", "/");
                                                    _item_editorloadPath.stringValue = path;
                                                }
                                                else
                                                {
                                                    Debug.LogError("Invalid Path: " + path);
                                                }
                                            }
                                        }
                                        //line 3: group name and base 64
                                        var _rect_groupName = _rect;
                                        _rect_groupName.y += singleLine * 2;
                                        _rect_groupName.width -= 30;
                                        _rect_groupName.width -= 125;
                                        EditorGUI.PropertyField(_rect_groupName, _item_groupname, new GUIContent("GroupName"));
                                        var _rect_base64 = _rect;
                                        _rect_base64.y += singleLine * 2;
                                        _rect_base64.x += _rect_groupName.width + 5;
                                        _rect_base64.width = 120;
                                        _item_base64.boolValue = EditorGUI.ToggleLeft(_rect_base64, new GUIContent("Value Is Base64", I18Ns.JsonB64_Tips), _item_base64.boolValue);
                                        //delete
                                        var _rect_del_btn = _rect;
                                        _rect_del_btn.width = 20;
                                        _rect_del_btn.x += _rect.width - 25;
                                        _rect_del_btn.height += singleLine * 2;
                                        if (GUI.Button(_rect_del_btn, new GUIContent("×", "Delete")))
                                        {
                                            item_json_dict.DeleteArrayElementAtIndex(i);
                                        }
                                    }
                                }
                                var rect_json_add_btn = rect;
                                rect_json_add_btn.y += (base_line * singleLine) + ((singleLine * 3.5f) * item_json_dict.arraySize);
                                rect_json_add_btn.x += 130;
                                rect_json_add_btn.width = 110;
                                if (GUI.Button(rect_json_add_btn, "Add Json Dict"))
                                {
                                    int _index = item_json_dict.arraySize;
                                    item_json_dict.InsertArrayElementAtIndex(_index);
                                    var _item = item_json_dict.GetArrayElementAtIndex(_index);
                                    var _item_loadPath = _item.FindPropertyRelative("LoadPath");
                                    var _item_base64 = _item.FindPropertyRelative("Base64Value");
                                    var _item_groupName = _item.FindPropertyRelative("GroupName");
                                    var _item_editorLoadPath = _item.FindPropertyRelative("EditorLoadPath");

                                    _item_loadPath.stringValue = string.Empty;
                                    _item_editorLoadPath.stringValue = string.Empty;
                                    _item_base64.boolValue = false;
                                    _item_groupName.stringValue = I18NConst.DefaultGroupName;
                                }
                                base_line += (item_json_dict.arraySize * 3.5f) + 1.5f;

                                //line 4 Asset Dicts
                                var rect_asset_dict_title = rect;
                                rect_asset_dict_title.y += (base_line) * singleLine;
                                rect_asset_dict_title.width = 125;
                                EditorGUI.LabelField(rect_asset_dict_title, new GUIContent("Asset Dict"));

                                if (item_asset_dict.arraySize > 0)
                                {
                                    var _rect_base = rect;
                                    _rect_base.y += base_line * singleLine;
                                    for (var i = 0; i < item_asset_dict.arraySize; i++)
                                    {
                                        var _rect = _rect_base;
                                        _rect.x += 130;
                                        _rect.y += singleLine * i;
                                        _rect.width -= 130;

                                        SerializedProperty _item_data = item_asset_dict.GetArrayElementAtIndex(i);
                                        SerializedProperty _item_asset = _item_data.FindPropertyRelative("Asset");
                                        SerializedProperty _item_groupName = _item_data.FindPropertyRelative("GroupName");

                                        var _rect_groupName_title = _rect;
                                        _rect_groupName_title.width = 85;
                                        EditorGUI.LabelField(_rect_groupName_title, new GUIContent("GroupName"));

                                        var _rect_groupName = _rect;
                                        _rect_groupName.x += 90;
                                        _rect_groupName.width = 135;
                                        EditorGUI.PropertyField(_rect_groupName, _item_groupName, GUIContent.none);

                                        var _rect_asset = _rect;
                                        _rect_asset.x += 90 + 135 + 5;
                                        _rect_asset.width = 160;
                                        EditorGUI.PropertyField(_rect_asset, _item_asset, GUIContent.none);

                                        var _rect_btn_del = _rect;
                                        _rect_btn_del.x += 90 + 135 + 5 + 160 + 5;
                                        _rect_btn_del.width = 25;
                                        if (GUI.Button(_rect_btn_del, new GUIContent("×", "Delete")))
                                        {
                                            item_asset_dict.DeleteArrayElementAtIndex(i);
                                        }
                                    }
                                }

                                var rect_asset_btn_add = rect;
                                rect_asset_btn_add.y += (base_line + item_asset_dict.arraySize) * singleLine;
                                rect_asset_btn_add.x += 130;
                                rect_asset_btn_add.width = 110;
                                if (GUI.Button(rect_asset_btn_add, "Add Asset Dict"))
                                {
                                    int _index = item_asset_dict.arraySize;
                                    item_asset_dict.InsertArrayElementAtIndex(_index);
                                    var _item = item_asset_dict.GetArrayElementAtIndex(_index);
                                    var _item_asset = _item.FindPropertyRelative("Asset");
                                    var _item_group = _item.FindPropertyRelative("GroupName");

                                    _item_asset.objectReferenceValue = null;
                                    _item_group.stringValue = I18NConst.DefaultGroupName;
                                }
                            };
                            mList_Regions.elementHeightCallback = (index) =>
                            {
                                SerializedProperty itemData = mList_Regions.serializedProperty.GetArrayElementAtIndex(index);
                                SerializedProperty item_bind_language = itemData.FindPropertyRelative("BindLanguage");
                                SerializedProperty item_json_dict = itemData.FindPropertyRelative("JsonDicts");
                                SerializedProperty item_asset_dict = itemData.FindPropertyRelative("AssetDicts");
                                float line = 1;
                                //绑定语言
                                line += item_bind_language.arraySize + 1.5f;
                                //全局Json字典
                                line += (item_json_dict.arraySize * 3.5f) + 1.5f;
                                //Asset字典
                                line += (item_asset_dict.arraySize) + 1;

                                return (EditorGUIUtility.singleLineHeight + 2) * line + 2;
                            };
                            mList_Regions.onAddCallback = (list) =>
                            {
                                if (list.serializedProperty != null)
                                {
                                    list.serializedProperty.arraySize++;
                                    list.index = list.serializedProperty.arraySize - 1;

                                    SerializedProperty itemData = list.serializedProperty.GetArrayElementAtIndex(list.index);
                                    SerializedProperty item_name = itemData.FindPropertyRelative("Name");
                                    SerializedProperty item_bind_lan = itemData.FindPropertyRelative("BindLanguage");
                                    SerializedProperty item_json = itemData.FindPropertyRelative("JsonDicts");
                                    SerializedProperty item_asset = itemData.FindPropertyRelative("AssetDicts");
                                    item_name.stringValue = string.Empty;
                                    item_bind_lan.ClearArray();
                                    item_json.ClearArray();
                                    item_asset.ClearArray();
                                }
                                else
                                {
                                    ReorderableList.defaultBehaviours.DoAddButton(list);
                                }
                            };
                            mList_Regions.drawHeaderCallback = (rect) =>
                            {
                                EditorGUI.LabelField(rect, I18Ns.RegionList);
                            };
                        }

                        GUILayout.Space(10);
                        EditorGUILayout.PropertyField(mConfig_SerObj.FindProperty("EnableI18N"));
                        EditorGUILayout.PropertyField(mConfig_SerObj.FindProperty("DefaultRegion"), GUILayout.MaxWidth(300));
                        EditorGUILayout.PropertyField(mConfig_SerObj.FindProperty("AutomaticMatchingBySystemLanaguage"), new GUIContent("Auto Match", "Automatically match regions according to system language"));
                        GUILayout.Space(10);
                        mList_Regions.DoLayoutList();

                        if (mConfig_SerObj != null)
                        {
                            mConfig_SerObj.ApplyModifiedProperties();
                        }
                    }
                    EditorGUILayout.EndVertical();
                },
                deactivateHandler = () =>
                {
                    if (mConfig != null)
                    {
                        EditorUtility.SetDirty(mConfig);
                        AssetDatabase.SaveAssets();
                        AssetDatabase.Refresh();
                    }
                },
            });
        }
Beispiel #2
0
    public override void OnInspectorGUI()
    {
        GUILayout.Space(10);
        EditorGUI.indentLevel += 1;
        SerializedProperty lifeScene    = serializedObject.FindProperty("LifeSceneNames");
        SerializedProperty numberLS     = serializedObject.FindProperty("numberLS");
        LifeSceneManager   lifeScenesLS = LifeSceneManager.Instance;

        lifeScenesLS.UpdateLS();

        if (numberLS.intValue != lifeScenesLS.LifeSceneNames.Length)
        {
            lifeScene.ClearArray();
            for (int i = 0; i < lifeScenesLS.LifeSceneNames.Length; ++i)
            {
                lifeScene.InsertArrayElementAtIndex(i);
                lifeScene.GetArrayElementAtIndex(i - 1).objectReferenceValue = lifeScenesLS.LifeSceneNames[i];
            }
            numberLS.intValue = lifeScenesLS.LifeSceneNames.Length;
        }

        if (lifeScene.arraySize == 0)
        {
            lifeScene.InsertArrayElementAtIndex(0);
            lifeScene.GetArrayElementAtIndex(lifeScene.arraySize - 1).objectReferenceValue = null;
        }

        for (int i = 0; i < lifeScene.arraySize; ++i)
        {
            GUILayout.BeginHorizontal();
            //EditorGUILayout.PropertyField(lifeScene.GetArrayElementAtIndex(i), new GUIContent(""), true);
            GUI.enabled = false;
            EditorGUILayout.ObjectField(new GUIContent(""), lifeScene.GetArrayElementAtIndex(i).objectReferenceValue, typeof(GameObject), true);
            GUI.enabled = true;
            if (GUILayout.Button("-", EditorStyles.miniButtonMid, GUILayout.ExpandWidth(false)))
            {
                if (i >= 0)
                {
                    GameObject.DestroyImmediate(lifeScene.GetArrayElementAtIndex(i).objectReferenceValue);
                    //GameObject deleteLS = GameObject.Find(lifeScene.GetArrayElementAtIndex(i).stringValue);
                    //GameObject.DestroyImmediate(deleteLS);
                    lifeScenesLS.LSnames.Remove(lifeScene.GetArrayElementAtIndex(i).objectReferenceValue as GameObject);
                    lifeScene.GetArrayElementAtIndex(i).objectReferenceValue = null;
                    lifeScene.DeleteArrayElementAtIndex(i);
                }
                GUILayout.EndHorizontal();
                break;
            }

            GUILayout.Space(5);
            GUILayout.EndHorizontal();
        }

        if (lifeScene.isInstantiatedPrefab)
        {
            SetBoldDefaultFont(lifeScene.prefabOverride);
        }
        GUILayout.Space(5);
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Add LifeScene", EditorStyles.miniButton, GUILayout.ExpandWidth(false), GUILayout.Width(100)))
        {
            //lifeScene.InsertArrayElementAtIndex(lifeScene.arraySize - 1);
            //lifeScene.GetArrayElementAtIndex(lifeScene.arraySize - 1).stringValue = "";
            EditorWindow.GetWindow(typeof(LifeSceneWindow), false, "Life Scene");
        }

        /*if (GUILayout.Button("Sort LifeScenes", EditorStyles.miniButton, GUILayout.ExpandWidth(false), GUILayout.Width(100)))
         * {
         *  names.Clear();
         *  for (int i = 0; i < lifeScene.arraySize; ++i)
         *  {
         *      names.Add(lifeScene.GetArrayElementAtIndex(i).objectReferenceValue as GameObject);
         *  }
         *  GameObject[] names1 = names.ToArray();
         *  Array.Sort(names1, (target as LifeSceneManager).CompareObNames);
         *  for (int i = 0; i < lifeScene.arraySize; ++i)
         *  {
         *      lifeScene.GetArrayElementAtIndex(i).objectReferenceValue = names1[i];
         *  }
         * }*/

        EditorGUI.indentLevel -= 1;
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.Space(5);

        serializedObject.ApplyModifiedProperties();
    }
Beispiel #3
0
 /// <inheritdoc/>
 public void Clear()
 {
     _arrayProperty.ClearArray();
 }
    public override void OnInspectorGUI()
    {
        targetObject.Update();

        //creates GUI tab
        tab = GUILayout.Toolbar(tab, tabTitles);

        switch (tab)
        {
        //basic vehicle stuff
        case 0:
            getVehicleValue();
            break;

        //wheel stuff
        case 1:
            //creates a drop down memnu with each steering method
            steeringMethod.intValue = EditorGUILayout.Popup("Steering Method", steeringMethod.intValue, steeringMethodMenu);

            //creates a feild to input prefab/mesh to create a new vehicle
            wheelMesh = (GameObject)EditorGUILayout.ObjectField("Wheel Mesh", wheelMesh, typeof(GameObject));

            //adds wheel
            if (GUILayout.Button("Add Wheel"))
            {
                makeWheel(wheelMesh);
            }

            //mirrors wheel from +x side to the -x side
            if (GUILayout.Button("Mirror Wheel"))
            {
                mirrorObj("wheel");
            }

            getWheels();
            break;

        //turret Stuff
        case 2:
            label("Adding Turret");

            //creates feilds for adding another turret
            turretMesh   = (GameObject)EditorGUILayout.ObjectField("Turret mesh", turretMesh, typeof(GameObject));
            barrelMesh   = (GameObject)EditorGUILayout.ObjectField("Barrel mesh", barrelMesh, typeof(GameObject));
            turretParent = (GameObject)EditorGUILayout.ObjectField("Turret Parent", turretParent, typeof(GameObject));

            //adds a turret
            if (GUILayout.Button("Add Turret"))
            {
                GameObject turret = Instantiate(turretTemplate, Vector3.zero, new Quaternion(), turretParent.transform);
                turret.name = "turret";
                Instantiate(turretMesh, turret.transform.position, turret.transform.rotation, turret.transform);
                Instantiate(barrelMesh, turret.transform.position, turret.transform.rotation, turret.transform);
            }

            //gets all the turret and displays turret information
            getTurrets();
            break;

        //misc stuff
        case 3:

            //creates a dropdown menu that shows antenna settings
            miscDropDowns[0] = EditorGUILayout.Foldout(miscDropDowns[0], "Antenna");

            if (miscDropDowns[0])
            {
                //creates feild to imput prefab/meshs to add an antenna
                antennaProp = (GameObject)EditorGUILayout.ObjectField("Antenna prefab", antennaProp, typeof(GameObject));
                miscParent  = (GameObject)EditorGUILayout.ObjectField("Parent", miscParent, typeof(GameObject));

                if (GUILayout.Button("Add Antenna"))
                {
                    GameObject antennaTemp = Instantiate(antennaProp, Vector3.zero, new Quaternion(), miscParent.transform);
                    antennaProp.name = "antenna";
                    antennaProp.tag  = "prop";
                    //checks if the input is a mesh with or without the antenna script
                    if (antennaTemp.GetComponent <antenna>() == null)
                    {
                        antenna component = antennaTemp.AddComponent(typeof(antenna)) as antenna;
                    }
                }
            }

            //creates a drop down menu with
            miscDropDowns[1] = EditorGUILayout.Foldout(miscDropDowns[1], "Lights");

            if (miscDropDowns[1])
            {
                lightProp  = (GameObject)EditorGUILayout.ObjectField("Light Prefab", lightProp, typeof(GameObject));
                miscParent = (GameObject)EditorGUILayout.ObjectField("Parent", miscParent, typeof(GameObject));

                if (GUILayout.Button("Add Light"))
                {
                    GameObject lightTemp = Instantiate(lightProp, Vector3.zero, new Quaternion(), miscParent.transform);
                    lightTemp.name = "light";
                    lightTemp.tag  = "prop";
                }

                if (GUILayout.Button("Mirror Lights"))
                {
                    mirrorObj("light");
                }
            }

            //updates the misc array
            int miscCount = 0;
            miscSerialized.ClearArray();
            for (int i1 = 0; i1 < v.transform.childCount; i1++)
            {
                if (v.transform.GetChild(i1).tag == "prop")
                {
                    miscSerialized.InsertArrayElementAtIndex(miscCount);
                    miscSerialized.GetArrayElementAtIndex(miscCount).objectReferenceValue = v.transform.GetChild(i1).gameObject;
                    miscCount += 1;
                }
            }
            break;
        }


        //update modified values
        targetObject.ApplyModifiedProperties();
        try
        {
            if (GUI.changed)
            {
                EditorUtility.SetDirty(v);
                EditorSceneManager.MarkSceneDirty(v.gameObject.scene);
            }
        }
        catch
        {
        }
    }
        // This code is generally the same as used in the DynamicDNAConverterCustomizer
        // Probably worth breaking it out at some point and having it geenric
        protected void CreateBonePoseCallback(UMAData umaData)
        {
            avatarDNAisDirty = false;
            UMABonePose bonePose = ScriptableObject.CreateInstance <UMABonePose>();

            UMAData     umaPreDNA       = tempAvatarPreDNA.GetComponent <UMADynamicAvatar>().umaData;
            UMAData     umaPostDNA      = tempAvatarPostDNA.GetComponent <UMADynamicAvatar>().umaData;
            UMADnaBase  activeDNA       = umaPostDNA.umaRecipe.GetDna(selectedDNAHash);
            UMASkeleton skeletonPreDNA  = umaPreDNA.skeleton;
            UMASkeleton skeletonPostDNA = umaPostDNA.skeleton;

            if (poseSaveIndex < 0)
            {
                poseSaveName = startingPoseName;

                // Now that StartingPose has been generated
                // add the active DNA to the pre DNA avatar
                // UMA2.8+ Lots of converters can use the same DNA now
                //UMA2.8+ FixDNAPrefabs raceData.GetConverter(s) now returns IDNAConverter([])
                IDNAConverter[] activeConverters = sourceUMA.umaRecipe.raceData.GetConverters(sourceUMA.umaRecipe.GetDna(selectedDNAHash));
                //umaPreDNA.umaRecipe.raceData.dnaConverterList = new DnaConverterBehaviour[1];
                //umaPreDNA.umaRecipe.raceData.dnaConverterList[0] = activeConverter;
                umaPreDNA.umaRecipe.raceData.dnaConverterList = activeConverters;
                umaPreDNA.umaRecipe.raceData.UpdateDictionary();
                umaPreDNA.umaRecipe.EnsureAllDNAPresent();
                umaPreDNA.Dirty(true, false, true);
            }

            Transform transformPreDNA;
            Transform transformPostDNA;
            bool      transformDirty;
            int       parentHash;

            foreach (int boneHash in skeletonPreDNA.BoneHashes)
            {
                skeletonPreDNA.TryGetBoneTransform(boneHash, out transformPreDNA, out transformDirty, out parentHash);
                skeletonPostDNA.TryGetBoneTransform(boneHash, out transformPostDNA, out transformDirty, out parentHash);

                if ((transformPreDNA == null) || (transformPostDNA == null))
                {
                    Debug.LogWarning("Bad bone hash in skeleton: " + boneHash);
                    continue;
                }

                if (!LocalTransformsMatch(transformPreDNA, transformPostDNA))
                {
                    bonePose.AddBone(transformPreDNA, transformPostDNA.localPosition, transformPostDNA.localRotation, transformPostDNA.localScale);
                }
            }

            int activeDNACount = activeDNA.Count;

            for (int i = 0; i < activeDNACount; i++)
            {
                activeDNA.SetValue(i, 0.5f);
            }

            AssetDatabase.CreateAsset(bonePose, folderPath + "/" + poseSaveName + ".asset");
            EditorUtility.SetDirty(bonePose);
            AssetDatabase.SaveAssets();

            poseSaveIndex++;
            if (poseSaveIndex < activeDNACount)
            {
                poseSaveName = activeDNA.Names[poseSaveIndex] + "_0";
                activeDNA.SetValue(poseSaveIndex, 0.0f);
                avatarDNAisDirty = true;
            }
            else if (poseSaveIndex < (activeDNACount * 2))
            {
                int dnaIndex = poseSaveIndex - activeDNACount;
                poseSaveName = activeDNA.Names[dnaIndex] + "_1";
                activeDNA.SetValue(dnaIndex, 1.0f);
                umaPostDNA.Dirty();
                avatarDNAisDirty = true;
            }
            else
            {
                UMAUtils.DestroySceneObject(tempAvatarPreDNA);
                UMAUtils.DestroySceneObject(tempAvatarPostDNA);

                // Build a prefab DNA Converter and populate it with the morph set
                string assetName = "Morph Set";
                string assetPath = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + ".asset");

                MorphSetDnaAsset asset           = CustomAssetUtility.CreateAsset <MorphSetDnaAsset>(assetPath, false);
                SerializedObject serializedAsset = new SerializedObject(asset);

                SerializedProperty startingPose = serializedAsset.FindProperty("startingPose");
                startingPose.objectReferenceValue = AssetDatabase.LoadAssetAtPath <UMABonePose>(folderPath + "/" + startingPoseName + ".asset");

                SerializedProperty morphSetArray = serializedAsset.FindProperty("dnaMorphs");
                morphSetArray.ClearArray();
                for (int i = 0; i < activeDNACount; i++)
                {
                    string posePairName = activeDNA.Names[i];

                    morphSetArray.InsertArrayElementAtIndex(i);
                    SerializedProperty posePair = morphSetArray.GetArrayElementAtIndex(i);

                    SerializedProperty dnaEntryName = posePair.FindPropertyRelative("dnaEntryName");
                    dnaEntryName.stringValue = posePairName;
                    SerializedProperty zeroPose = posePair.FindPropertyRelative("poseZero");
                    zeroPose.objectReferenceValue = AssetDatabase.LoadAssetAtPath <UMABonePose>(folderPath + "/" + posePairName + "_0.asset");
                    SerializedProperty onePose = posePair.FindPropertyRelative("poseOne");
                    onePose.objectReferenceValue = AssetDatabase.LoadAssetAtPath <UMABonePose>(folderPath + "/" + posePairName + "_1.asset");
                }
                serializedAsset.ApplyModifiedPropertiesWithoutUndo();

                // Build a prefab DNA Converter and populate it with the morph set
                string prefabName = "Converter Prefab";
                string prefabPath = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + prefabName + ".prefab");

                GameObject tempConverterPrefab          = new GameObject(prefabName);
                MorphSetDnaConverterBehaviour converter = tempConverterPrefab.AddComponent <MorphSetDnaConverterBehaviour>();
                SerializedObject serializedConverter    = new SerializedObject(converter);

                SerializedProperty morphSet = serializedAsset.FindProperty("morphSet");
                morphSet.objectReferenceValue = AssetDatabase.LoadAssetAtPath <MorphSetDnaAsset>(assetPath);

                serializedConverter.ApplyModifiedPropertiesWithoutUndo();
#if UNITY_2018_3_OR_NEWER
                PrefabUtility.SaveAsPrefabAsset(tempConverterPrefab, prefabPath);
#else
                PrefabUtility.CreatePrefab(prefabPath, tempConverterPrefab);
#endif
                DestroyImmediate(tempConverterPrefab, false);
            }
        }
    /// <summary>
    /// Apply the editor's state and data to the serializedLevel and save it.
    /// </summary>
    void Save()
    {
        // Set values of serializedLevel's top-level properties
        serializedLevel.FindProperty("gridWidth").intValue    = gridWidth;
        serializedLevel.FindProperty("gridHeight").intValue   = gridHeight;
        serializedLevel.FindProperty("levelName").stringValue = name;

        // reset the presetColor_ bools
        serializedLevel.FindProperty("presetColor_blue").boolValue = false;


        // get the grid property from the serializedLevel and clear its contents
        SerializedProperty gridProperty = serializedLevel.FindProperty("grid");

        gridProperty.ClearArray();

        // fill the serializedLevel's grid with data from the window's grid[,]
        for (int i = 0; i < gridWidth * gridHeight; ++i)
        {
            gridProperty.InsertArrayElementAtIndex(i);
            SerializedProperty serializedCell = gridProperty.GetArrayElementAtIndex(i);

            // find x and y grid positions of the cell with he formula : i = x * gridHeight + y
            int gridX = i / gridHeight;
            int gridY = i % gridHeight;


            serializedCell.FindPropertyRelative("x").intValue = grid[gridX, gridY].x;
            serializedCell.FindPropertyRelative("y").intValue = grid[gridX, gridY].y;

            serializedCell.FindPropertyRelative("hole").boolValue = grid[gridX, gridY].hole;

            serializedCell.FindPropertyRelative("presetContent").boolValue = grid[gridX, gridY].presetContent;

            serializedCell.FindPropertyRelative("content").intValue = (int)grid[gridX, gridY].content;


            // if we find a cell that has a preset candy color, we set the corresponding bool on the seriliazedlevel
            if (grid[gridX, gridY].content != LevelEditorCellContent.random)
            {
                switch (grid[gridX, gridY].content)
                {
                case LevelEditorCellContent.candy_blue:
                    serializedLevel.FindProperty("presetColor_blue").boolValue = true;
                    break;

                case LevelEditorCellContent.candy_red:
                    break;

                case LevelEditorCellContent.candy_green:
                    break;

                case LevelEditorCellContent.candy_orange:
                    break;

                case LevelEditorCellContent.candy_yellow:
                    break;
                }

                // add the GridManager.CellContent to the array
                if (!presetColorsList.Contains(grid[gridX, gridY].content))
                {
                    presetColorsList.Add(grid[gridX, gridY].content);
                }
            }
        }

        SerializedProperty presetColorsArray = serializedLevel.FindProperty("presetColors");

        presetColorsArray.ClearArray();

        for (int i = 0; i < presetColorsList.Count; ++i)
        {
            presetColorsArray.InsertArrayElementAtIndex(i);
            presetColorsArray.GetArrayElementAtIndex(i).intValue = (int)presetColorsList[i];
        }

        // apply the modified properties to the original SerializedObject
        serializedLevel.ApplyModifiedProperties();
    }
Beispiel #7
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            VRTK_SDKManager sdkManager = (VRTK_SDKManager)target;

            EditorGUILayout.PropertyField(serializedObject.FindProperty("persistOnLoad"));

            const string manageNowButtonText = "Manage Now";

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Scripting Define Symbols", false);

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.BeginChangeCheck();
                    bool autoManage = EditorGUILayout.Toggle(
                        VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("autoManageScriptDefines", "Auto Manage"),
                        sdkManager.autoManageScriptDefines,
                        GUILayout.ExpandWidth(false)
                        );
                    if (EditorGUI.EndChangeCheck())
                    {
                        serializedObject.FindProperty("autoManageScriptDefines").boolValue = autoManage;
                        serializedObject.ApplyModifiedProperties();
                        sdkManager.ManageScriptingDefineSymbols(false, true);
                    }

                    using (new EditorGUI.DisabledGroupScope(sdkManager.autoManageScriptDefines))
                    {
                        GUIContent manageNowGUIContent = new GUIContent(
                            manageNowButtonText,
                            "Manage the scripting define symbols defined by the installed SDKs."
                            + (sdkManager.autoManageScriptDefines
                                   ? "\n\nThis button is disabled because the SDK Manager is set up to manage the scripting define symbols automatically."
                               + " Disable the checkbox on the left to allow managing them manually instead."
                                   : "")
                            );
                        if (GUILayout.Button(manageNowGUIContent, GUILayout.MaxHeight(GUI.skin.label.CalcSize(manageNowGUIContent).y)))
                        {
                            sdkManager.ManageScriptingDefineSymbols(true, true);
                        }
                    }
                }

                using (new EditorGUILayout.VerticalScope("Box"))
                {
                    VRTK_EditorUtilities.AddHeader("Active Symbols Without SDK Classes", false);

                    VRTK_SDKInfo[] availableSDKInfos = VRTK_SDKManager
                                                       .AvailableSystemSDKInfos
                                                       .Concat(VRTK_SDKManager.AvailableBoundariesSDKInfos)
                                                       .Concat(VRTK_SDKManager.AvailableHeadsetSDKInfos)
                                                       .Concat(VRTK_SDKManager.AvailableControllerSDKInfos)
                                                       .ToArray();
                    HashSet <string> sdkSymbols = new HashSet <string>(availableSDKInfos.Select(info => info.description.symbol));
                    IGrouping <BuildTargetGroup, VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo>[] availableGroupedPredicateInfos = VRTK_SDKManager
                                                                                                                                        .AvailableScriptingDefineSymbolPredicateInfos
                                                                                                                                        .GroupBy(info => info.attribute.buildTargetGroup)
                                                                                                                                        .ToArray();
                    foreach (IGrouping <BuildTargetGroup, VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo> grouping in availableGroupedPredicateInfos)
                    {
                        VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo[] possibleActiveInfos = grouping
                                                                                                   .Where(info => !sdkSymbols.Contains(info.attribute.symbol) &&
                                                                                                          grouping.Except(new[] { info })
                                                                                                          .All(predicateInfo => !(predicateInfo.methodInfo == info.methodInfo &&
                                                                                                                                  sdkSymbols.Contains(predicateInfo.attribute.symbol))))
                                                                                                   .OrderBy(info => info.attribute.symbol)
                                                                                                   .ToArray();
                        if (possibleActiveInfos.Length == 0)
                        {
                            continue;
                        }

                        EditorGUI.indentLevel++;

                        BuildTargetGroup targetGroup = grouping.Key;
                        isBuildTargetActiveSymbolsFoldOut[targetGroup] = EditorGUI.Foldout(
                            EditorGUILayout.GetControlRect(),
                            isBuildTargetActiveSymbolsFoldOut[targetGroup],
                            targetGroup.ToString(),
                            true
                            );

                        if (isBuildTargetActiveSymbolsFoldOut[targetGroup])
                        {
                            foreach (VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo predicateInfo in possibleActiveInfos)
                            {
                                int symbolIndex = sdkManager
                                                  .activeScriptingDefineSymbolsWithoutSDKClasses
                                                  .FindIndex(attribute => attribute.symbol == predicateInfo.attribute.symbol);
                                string symbolLabel = predicateInfo.attribute.symbol.Remove(
                                    0,
                                    SDK_ScriptingDefineSymbolPredicateAttribute.RemovableSymbolPrefix.Length
                                    );

                                if (!(bool)predicateInfo.methodInfo.Invoke(null, null))
                                {
                                    symbolLabel += " (not installed)";
                                }

                                EditorGUI.BeginChangeCheck();
                                bool isSymbolActive = EditorGUILayout.ToggleLeft(symbolLabel, symbolIndex != -1);
                                if (EditorGUI.EndChangeCheck())
                                {
                                    Undo.RecordObject(sdkManager, "Active Symbol Change");
                                    if (isSymbolActive)
                                    {
                                        sdkManager.activeScriptingDefineSymbolsWithoutSDKClasses.Add(predicateInfo.attribute);
                                    }
                                    else
                                    {
                                        sdkManager.activeScriptingDefineSymbolsWithoutSDKClasses.RemoveAt(symbolIndex);
                                    }
                                    sdkManager.ManageScriptingDefineSymbols(false, true);
                                }
                            }
                        }

                        EditorGUI.indentLevel--;
                    }
                }

                VRTK_EditorUtilities.DrawUsingDestructiveStyle(GUI.skin.button, style =>
                {
                    GUIContent clearSymbolsGUIContent = new GUIContent(
                        "Remove All Symbols",
                        "Remove all scripting define symbols of VRTK. This is handy if you removed the SDK files from your project but still have"
                        + " the symbols defined which results in compile errors."
                        + "\nIf you have the above checkbox enabled the symbols will be managed automatically after clearing them. Otherwise hit the"
                        + " '" + manageNowButtonText + "' button to add the symbols for the currently installed SDKs again."
                        );

                    if (GUILayout.Button(clearSymbolsGUIContent, style))
                    {
                        BuildTargetGroup[] targetGroups = VRTK_SharedMethods.GetValidBuildTargetGroups();

                        foreach (BuildTargetGroup targetGroup in targetGroups)
                        {
                            string[] currentSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup)
                                                      .Split(';')
                                                      .Distinct()
                                                      .OrderBy(symbol => symbol, StringComparer.Ordinal)
                                                      .ToArray();
                            string[] newSymbols = currentSymbols
                                                  .Where(symbol => !symbol.StartsWith(SDK_ScriptingDefineSymbolPredicateAttribute.RemovableSymbolPrefix, StringComparison.Ordinal))
                                                  .ToArray();

                            if (currentSymbols.SequenceEqual(newSymbols))
                            {
                                continue;
                            }

                            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", newSymbols));

                            string[] removedSymbols = currentSymbols.Except(newSymbols).ToArray();
                            if (removedSymbols.Length > 0)
                            {
                                VRTK_Logger.Info(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.SCRIPTING_DEFINE_SYMBOLS_REMOVED, targetGroup, string.Join(", ", removedSymbols)));
                            }
                        }
                    }
                });
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Script Aliases", false);
                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("scriptAliasLeftController"),
                    VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("scriptAliasLeftController", "Left Controller")
                    );
                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("scriptAliasRightController"),
                    VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("scriptAliasRightController", "Right Controller")
                    );
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Setups", false);

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.BeginChangeCheck();
                    bool autoManage = EditorGUILayout.Toggle(
                        VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("autoManageVRSettings"),
                        sdkManager.autoManageVRSettings,
                        GUILayout.ExpandWidth(false)
                        );
                    if (EditorGUI.EndChangeCheck())
                    {
                        serializedObject.FindProperty("autoManageVRSettings").boolValue = autoManage;
                        serializedObject.ApplyModifiedProperties();
                        sdkManager.ManageVRSettings(false);
                    }

                    using (new EditorGUI.DisabledGroupScope(sdkManager.autoManageVRSettings))
                    {
                        GUIContent manageNowGUIContent = new GUIContent(
                            manageNowButtonText,
                            "Manage the VR settings of the Player Settings to allow for all the installed SDKs."
                            + (sdkManager.autoManageVRSettings
                                   ? "\n\nThis button is disabled because the SDK Manager is set up to manage the VR Settings automatically."
                               + " Disable the checkbox on the left to allow managing them manually instead."
                                   : "")
                            );
                        if (GUILayout.Button(manageNowGUIContent, GUILayout.MaxHeight(GUI.skin.label.CalcSize(manageNowGUIContent).y)))
                        {
                            sdkManager.ManageVRSettings(true);
                        }
                    }
                }

                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("autoLoadSetup"),
                    VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("autoLoadSetup", "Auto Load")
                    );

                setupsList.DoLayoutList();

                GUIContent autoPopulateGUIContent = new GUIContent("Auto Populate", "Automatically populates the list of SDK Setups with Setups in the scene.");
                if (GUILayout.Button(autoPopulateGUIContent))
                {
                    SerializedProperty serializedProperty = setupsList.serializedProperty;
                    serializedProperty.ClearArray();
                    VRTK_SDKSetup[] setups = sdkManager.GetComponentsInChildren <VRTK_SDKSetup>(true)
                                             .Concat(VRTK_SharedMethods.FindEvenInactiveComponents <VRTK_SDKSetup>())
                                             .Distinct()
                                             .ToArray();

                    for (int index = 0; index < setups.Length; index++)
                    {
                        VRTK_SDKSetup setup = setups[index];
                        serializedProperty.InsertArrayElementAtIndex(index);
                        serializedProperty.GetArrayElementAtIndex(index).objectReferenceValue = setup;
                    }
                }

                if (sdkManager.setups.Length > 1)
                {
                    EditorGUILayout.HelpBox("Duplicated setups are removed automatically.", MessageType.Info);
                }

                if (Enumerable.Range(0, sdkManager.setups.Length).Any(IsSDKSetupNeverUsed))
                {
                    EditorGUILayout.HelpBox("Gray setups will never be loaded because either the SDK Setup isn't valid or there"
                                            + " is a valid Setup before it that uses any non-VR SDK.",
                                            MessageType.Warning);
                }
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Target Platform Group Exclusions", false);
                SerializedProperty excludeTargetGroups = serializedObject.FindProperty("excludeTargetGroups");
                excludeTargetGroups.arraySize = EditorGUILayout.IntField("Size", excludeTargetGroups.arraySize);
                for (int i = 0; i < excludeTargetGroups.arraySize; i++)
                {
                    EditorGUILayout.PropertyField(excludeTargetGroups.GetArrayElementAtIndex(i));
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
 protected virtual void ClearList(SerializedProperty listProperty) => listProperty.ClearArray();
Beispiel #9
0
 public static void Clear(this SerializedProperty arrayProperty)
 {
     arrayProperty.ClearArray();
     arrayProperty.serializedObject.ApplyModifiedProperties();
     EditorUtility.SetDirty(arrayProperty.serializedObject.targetObject);
 }
Beispiel #10
0
    public static void SetVRSDKs(string[] sdkNames)
    {
        Debug.Log("Setting virtual reality SDKs in PlayerSettings: ");
        if (sdkNames != null)
        {
            foreach (string s in sdkNames)
            {
                Debug.Log("- " + s);
            }
        }

        PlayerSettings[] playerSettings = Resources.FindObjectsOfTypeAll <PlayerSettings>();
        if (playerSettings == null)
        {
            return;
        }

        SerializedObject   playerSettingsSerializedObject = new SerializedObject(playerSettings);
        SerializedProperty settingsGroup = playerSettingsSerializedObject.FindProperty("m_BuildTargetVRSettings");

        if (settingsGroup == null)
        {
            return;
        }

        for (int i = 0; i < settingsGroup.arraySize; i++)
        {
            SerializedProperty settingVal = settingsGroup.GetArrayElementAtIndex(i);
            if (settingVal == null)
            {
                continue;
            }

            IEnumerator enumerator = settingVal.GetEnumerator();
            if (enumerator == null)
            {
                continue;
            }

            while (enumerator.MoveNext())
            {
                SerializedProperty property = (SerializedProperty)enumerator.Current;

                if (property != null && property.name == "m_BuildTarget")
                {
                    // only change setting on "Standalone" entry
                    if (property.stringValue != "Standalone")
                    {
                        break;
                    }
                }

                if (property != null && property.name == "m_Devices")
                {
                    property.ClearArray();
                    property.arraySize = (sdkNames != null) ? sdkNames.Length : 0;
                    for (int j = 0; j < property.arraySize; j++)
                    {
                        property.GetArrayElementAtIndex(j).stringValue = sdkNames[j];
                    }
                }
            }
        }

        playerSettingsSerializedObject.ApplyModifiedProperties();
    }
Beispiel #11
0
    static void SetGraphicsSettings()
    {
        Debug.Log("Setting Graphics Settings");

        const string     GraphicsSettingsAssetPath = "ProjectSettings/GraphicsSettings.asset";
        SerializedObject graphicsManager           = new SerializedObject(UnityEditor.AssetDatabase.LoadAllAssetsAtPath(GraphicsSettingsAssetPath)[0]);

        SerializedProperty deferred = graphicsManager.FindProperty("m_Deferred.m_Mode");

        deferred.enumValueIndex = 1;

        SerializedProperty deferredReflections = graphicsManager.FindProperty("m_DeferredReflections.m_Mode");

        deferredReflections.enumValueIndex = 1;

        SerializedProperty screenSpaceShadows = graphicsManager.FindProperty("m_ScreenSpaceShadows.m_Mode");

        screenSpaceShadows.enumValueIndex = 1;

        SerializedProperty legacyDeferred = graphicsManager.FindProperty("m_LegacyDeferred.m_Mode");

        legacyDeferred.enumValueIndex = 1;

        SerializedProperty depthNormals = graphicsManager.FindProperty("m_DepthNormals.m_Mode");

        depthNormals.enumValueIndex = 1;

        SerializedProperty motionVectors = graphicsManager.FindProperty("m_MotionVectors.m_Mode");

        motionVectors.enumValueIndex = 1;

        SerializedProperty lightHalo = graphicsManager.FindProperty("m_LightHalo.m_Mode");

        lightHalo.enumValueIndex = 1;

        SerializedProperty lensFlare = graphicsManager.FindProperty("m_LensFlare.m_Mode");

        lensFlare.enumValueIndex = 1;

#if ENV_SET_INCLUDED_SHADERS
        SerializedProperty alwaysIncluded = graphicsManager.FindProperty("m_AlwaysIncludedShaders");

#if ENV_SEARCH_FOR_SHADERS
        Resources.LoadAll("", typeof(Shader));
        System.Collections.Generic.List <Shader> foundShaders = Resources.FindObjectsOfTypeAll <Shader>()
                                                                .Where(s => { string name = s.name.ToLower(); return(0 == (s.hideFlags & HideFlags.DontSave)); })
                                                                .GroupBy(s => s.name)
                                                                .Select(g => g.First())
                                                                .ToList();
#else
        System.Collections.Generic.List <Shader> foundShaders = new System.Collections.Generic.List <Shader>();
#endif

        for (int shaderIdx = 0; shaderIdx < ensureTheseShadersAreAvailable.Length; ++shaderIdx)
        {
            if (foundShaders.Any(s => s.name == ensureTheseShadersAreAvailable[shaderIdx]))
            {
                continue;
            }
            Shader namedShader = Shader.Find(ensureTheseShadersAreAvailable[shaderIdx]);
            if (namedShader != null)
            {
                foundShaders.Add(namedShader);
            }
        }

        foundShaders.Sort((s1, s2) => s1.name.CompareTo(s2.name));

        alwaysIncluded.arraySize = foundShaders.Count;
        for (int shaderIdx = 0; shaderIdx < foundShaders.Count; ++shaderIdx)
        {
            alwaysIncluded.GetArrayElementAtIndex(shaderIdx).objectReferenceValue = foundShaders[shaderIdx];
        }
#endif

        SerializedProperty preloaded = graphicsManager.FindProperty("m_PreloadedShaders");
        preloaded.ClearArray();
        preloaded.arraySize = 0;

        SerializedProperty spritesDefaultMaterial = graphicsManager.FindProperty("m_SpritesDefaultMaterial");
        spritesDefaultMaterial.objectReferenceValue = Shader.Find("Sprites/Default");

        SerializedProperty renderPipeline = graphicsManager.FindProperty("m_CustomRenderPipeline");
        renderPipeline.objectReferenceValue = null;

        SerializedProperty transparencySortMode = graphicsManager.FindProperty("m_TransparencySortMode");
        transparencySortMode.enumValueIndex = 0;

        SerializedProperty transparencySortAxis = graphicsManager.FindProperty("m_TransparencySortAxis");
        transparencySortAxis.vector3Value = Vector3.forward;

        SerializedProperty defaultRenderingPath = graphicsManager.FindProperty("m_DefaultRenderingPath");
        defaultRenderingPath.intValue = 1;

        SerializedProperty defaultMobileRenderingPath = graphicsManager.FindProperty("m_DefaultMobileRenderingPath");
        defaultMobileRenderingPath.intValue = 1;

        SerializedProperty tierSettings = graphicsManager.FindProperty("m_TierSettings");
        tierSettings.ClearArray();
        tierSettings.arraySize = 0;

#if ENV_SET_LIGHTMAP
        SerializedProperty lightmapStripping = graphicsManager.FindProperty("m_LightmapStripping");
        lightmapStripping.enumValueIndex = 1;

        SerializedProperty instancingStripping = graphicsManager.FindProperty("m_InstancingStripping");
        instancingStripping.enumValueIndex = 2;

        SerializedProperty lightmapKeepPlain = graphicsManager.FindProperty("m_LightmapKeepPlain");
        lightmapKeepPlain.boolValue = true;

        SerializedProperty lightmapKeepDirCombined = graphicsManager.FindProperty("m_LightmapKeepDirCombined");
        lightmapKeepDirCombined.boolValue = true;

        SerializedProperty lightmapKeepDynamicPlain = graphicsManager.FindProperty("m_LightmapKeepDynamicPlain");
        lightmapKeepDynamicPlain.boolValue = true;

        SerializedProperty lightmapKeepDynamicDirCombined = graphicsManager.FindProperty("m_LightmapKeepDynamicDirCombined");
        lightmapKeepDynamicDirCombined.boolValue = true;

        SerializedProperty lightmapKeepShadowMask = graphicsManager.FindProperty("m_LightmapKeepShadowMask");
        lightmapKeepShadowMask.boolValue = true;

        SerializedProperty lightmapKeepSubtractive = graphicsManager.FindProperty("m_LightmapKeepSubtractive");
        lightmapKeepSubtractive.boolValue = true;
#endif

#if ENV_SET_FOG
        SerializedProperty fogStripping = graphicsManager.FindProperty("m_FogStripping");
        fogStripping.enumValueIndex = 1;

        SerializedProperty fogKeepLinear = graphicsManager.FindProperty("m_FogKeepLinear");
        fogKeepLinear.boolValue = true;

        SerializedProperty fogKeepExp = graphicsManager.FindProperty("m_FogKeepExp");
        fogKeepExp.boolValue = true;

        SerializedProperty fogKeepExp2 = graphicsManager.FindProperty("m_FogKeepExp2");
        fogKeepExp2.boolValue = true;
#endif

        SerializedProperty albedoSwatchInfos = graphicsManager.FindProperty("m_AlbedoSwatchInfos");
        albedoSwatchInfos.ClearArray();
        albedoSwatchInfos.arraySize = 0;

        SerializedProperty lightsUseLinearIntensity = graphicsManager.FindProperty("m_LightsUseLinearIntensity");
        lightsUseLinearIntensity.boolValue = true;

        SerializedProperty lightsUseColorTemperature = graphicsManager.FindProperty("m_LightsUseColorTemperature");
        lightsUseColorTemperature.boolValue = true;

        graphicsManager.ApplyModifiedProperties();
    }
Beispiel #12
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            EditorGUI.BeginChangeCheck();

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PropertyField(colorMap);

                if (colorMap.objectReferenceValue)
                {
                    /*
                     * if (GUILayout.Button(new GUIContent(" Edit", EditorGUIUtility.IconContent(EditorGUIUtility.isProSkin ? "d_editicon.sml" : "editicon.sml").image), GUILayout.MaxWidth(70f)))
                     * {
                     *  Selection.activeObject = colorMap.objectReferenceValue;
                     * }
                     */
                    if (GUILayout.Button(new GUIContent(" New", EditorGUIUtility.IconContent(EditorGUIUtility.isProSkin ? "d_editicon.sml" : "editicon.sml").image), GUILayout.MaxWidth(70f)))
                    {
                        colorMap.objectReferenceValue = ColorMapEditor.NewColorMap();
                    }
                }
            }

            if (!colorMap.objectReferenceValue)
            {
                EditorGUILayout.HelpBox("No color map assigned", MessageType.Error);
                return;
            }

            if (colorMap.objectReferenceValue)
            {
                //EditorGUILayout.LabelField(string.Format("Area size: {0}x{1}", script.colorMap.bounds.size.x, script.colorMap.bounds.size.z));

                if (EditorUtility.IsPersistent(script.colorMap) == false)
                {
                    Action saveColorMap = new Action(SaveColorMap);
                    StylizedGrassGUI.DrawActionBox("  The color map asset has not been saved to a file\n  and can only be used in this scene", "Save", MessageType.Warning, saveColorMap);
                }

                if (script.colorMap.overrideTexture)
                {
                    EditorGUILayout.HelpBox("The assigned color map uses a texture override. Rendering a new/updated color map will revert this.", MessageType.Warning);
                }
            }

            EditorGUILayout.Space();

            StylizedGrassGUI.ParameterGroup.DrawHeader(new GUIContent("Render area"));

            using (new EditorGUILayout.VerticalScope(StylizedGrassGUI.ParameterGroup.Section))
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(terrainObjects);
                EditorGUI.indentLevel--;

                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.FlexibleSpace();
#if VEGETATION_STUDIO_PRO
                    if (GUILayout.Button("Add VSP mesh terrains"))
                    {
                        AwesomeTechnologies.MeshTerrains.MeshTerrain[] terrains = GameObject.FindObjectsOfType <AwesomeTechnologies.MeshTerrains.MeshTerrain>();

                        for (int i = 0; i < terrains.Length; i++)
                        {
                            if (script.terrainObjects.Contains(terrains[i].gameObject) == false)
                            {
                                script.terrainObjects.Add(terrains[i].gameObject);
                            }
                        }
                    }
#endif
                    if (GUILayout.Button("Add active terrains"))
                    {
                        Terrain[] terrains = Terrain.activeTerrains;

                        for (int i = 0; i < terrains.Length; i++)
                        {
                            if (script.terrainObjects.Contains(terrains[i].gameObject) == false)
                            {
                                script.terrainObjects.Add(terrains[i].gameObject);
                            }
                        }

                        RefreshLayerNames();
                    }
                    if (GUILayout.Button("Add child meshes"))
                    {
                        //All childs, recursive
                        MeshRenderer[] children = script.gameObject.GetComponentsInChildren <MeshRenderer>();

                        for (int i = 0; i < children.Length; i++)
                        {
                            if (script.terrainObjects.Contains(children[i].gameObject) == false)
                            {
                                script.terrainObjects.Add(children[i].gameObject);
                            }
                        }
                    }
                    if (GUILayout.Button("Clear"))
                    {
                        terrainObjects.ClearArray();
                    }
                }

                EditorGUILayout.Space();

                EditMode.DoEditModeInspectorModeButton(EditMode.SceneViewEditMode.Collider, "Edit Volume", EditorGUIUtility.IconContent("EditCollider"), GetBounds, this);
                script.colorMap.bounds.size   = EditorGUILayout.Vector3Field("Size", script.colorMap.bounds.size);
                script.colorMap.bounds.center = EditorGUILayout.Vector3Field("Center", script.colorMap.bounds.center);

                if (script.colorMap.bounds.size == Vector3.zero && terrainObjects.arraySize == 0)
                {
                    EditorGUILayout.HelpBox("The render area cannot be zero", MessageType.Error);
                }
                if (script.colorMap.bounds.size == Vector3.zero && terrainObjects.arraySize > 0)
                {
                    EditorGUILayout.HelpBox("The render area will be automatically calculate based on terrain size", MessageType.Info);
                }

                using (new EditorGUI.DisabledGroupScope(script.terrainObjects.Count == 0))
                {
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        GUILayout.FlexibleSpace();
                        if (GUILayout.Button("Calculate from terrain(s)"))
                        {
                            ColorMapEditor.ApplyUVFromTerrainBounds(colorMap.objectReferenceValue as GrassColorMap, script);
                            SceneView.RepaintAll();
                        }
                    }
                }
            }

            EditorGUILayout.Space();

            StylizedGrassGUI.ParameterGroup.DrawHeader(new GUIContent("Layer-based grass scale (experimental)"));
            using (new EditorGUILayout.VerticalScope(StylizedGrassGUI.ParameterGroup.Section))
            {
                DrawLayerHeightSettings();
            }

            EditorGUILayout.Space();

            StylizedGrassGUI.ParameterGroup.DrawHeader(new GUIContent("Rendering"));
            using (new EditorGUILayout.VerticalScope(StylizedGrassGUI.ParameterGroup.Section))
            {
                EditorGUILayout.PropertyField(useLayers);

                if (useLayers.boolValue)
                {
                    EditorGUILayout.PropertyField(renderLayer);

                    if (renderLayer.intValue == 0)
                    {
                        EditorGUILayout.HelpBox("The render layer is set to \"Nothing\", no objects will be rendered into the color map", MessageType.Error);
                    }
                }

                using (new EditorGUILayout.HorizontalScope())
                {
                    resIdx.intValue = EditorGUILayout.Popup("Resolution", resIdx.intValue, ColorMapEditor.reslist, new GUILayoutOption[0]);
                    if (GUILayout.Button("Render"))
                    {
                        ColorMapEditor.RenderColorMap((GrassColorMapRenderer)target);
                    }
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                resolution.intValue = ColorMapEditor.IndexToResolution(resIdx.intValue);
                serializedObject.ApplyModifiedProperties();
            }

            EditorGUILayout.LabelField("- Staggart Creations -", EditorStyles.centeredGreyMiniLabel);
        }
Beispiel #13
0
    private static void SetGraphicsSettings()
    {
        VRC.Core.Logger.Log("Setting Graphics Settings", VRC.Core.DebugLevel.All);

        const string     graphicsSettingsAssetPath = "ProjectSettings/GraphicsSettings.asset";
        SerializedObject graphicsManager           = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath(graphicsSettingsAssetPath)[0]);

        SerializedProperty deferred = graphicsManager.FindProperty("m_Deferred.m_Mode");

        deferred.enumValueIndex = 1;

        SerializedProperty deferredReflections = graphicsManager.FindProperty("m_DeferredReflections.m_Mode");

        deferredReflections.enumValueIndex = 1;

        SerializedProperty screenSpaceShadows = graphicsManager.FindProperty("m_ScreenSpaceShadows.m_Mode");

        screenSpaceShadows.enumValueIndex = 1;

        SerializedProperty legacyDeferred = graphicsManager.FindProperty("m_LegacyDeferred.m_Mode");

        legacyDeferred.enumValueIndex = 1;

        SerializedProperty depthNormals = graphicsManager.FindProperty("m_DepthNormals.m_Mode");

        depthNormals.enumValueIndex = 1;

        SerializedProperty motionVectors = graphicsManager.FindProperty("m_MotionVectors.m_Mode");

        motionVectors.enumValueIndex = 1;

        SerializedProperty lightHalo = graphicsManager.FindProperty("m_LightHalo.m_Mode");

        lightHalo.enumValueIndex = 1;

        SerializedProperty lensFlare = graphicsManager.FindProperty("m_LensFlare.m_Mode");

        lensFlare.enumValueIndex = 1;

        #if ENV_SET_INCLUDED_SHADERS && VRC_CLIENT
        // clear GraphicsSettings->Always Included Shaders - these cause a +5s app startup time increase on Quest.
        // include Shader objects as resources instead
        SerializedProperty alwaysIncluded = graphicsManager.FindProperty("m_AlwaysIncludedShaders");
        alwaysIncluded.arraySize = 0;

        #if ENV_SEARCH_FOR_SHADERS
        Resources.LoadAll("", typeof(Shader));
        System.Collections.Generic.List <Shader> foundShaders = Resources.FindObjectsOfTypeAll <Shader>()
                                                                .Where(s => { string name = s.name.ToLower(); return(0 == (s.hideFlags & HideFlags.DontSave)); })
                                                                .GroupBy(s => s.name)
                                                                .Select(g => g.First())
                                                                .ToList();
        #else
        List <Shader> foundShaders = new List <Shader>();
        #endif

        foreach (string shader in ensureTheseShadersAreAvailable.OrderBy(s => s, StringComparer.Ordinal))
        {
            if (foundShaders.Any(s => s.name == shader))
            {
                continue;
            }

            Shader namedShader = Shader.Find(shader);
            if (namedShader != null)
            {
                foundShaders.Add(namedShader);
            }
        }

        foundShaders.Sort((s1, s2) => string.Compare(s1.name, s2.name, StringComparison.Ordinal));

        // populate Resources list of "always included shaders"
        ShaderAssetList alwaysIncludedShaders = AssetDatabase.LoadAssetAtPath <ShaderAssetList>("Assets/Resources/AlwaysIncludedShaders.asset");
        alwaysIncludedShaders.Shaders = new Shader[foundShaders.Count];
        for (int shaderIdx = 0; shaderIdx < foundShaders.Count; ++shaderIdx)
        {
            alwaysIncludedShaders.Shaders[shaderIdx] = foundShaders[shaderIdx];
        }

        EditorUtility.SetDirty(alwaysIncludedShaders);
        #endif

        SerializedProperty preloaded = graphicsManager.FindProperty("m_PreloadedShaders");
        preloaded.ClearArray();
        preloaded.arraySize = 0;

        SerializedProperty spritesDefaultMaterial = graphicsManager.FindProperty("m_SpritesDefaultMaterial");
        spritesDefaultMaterial.objectReferenceValue = Shader.Find("Sprites/Default");

        SerializedProperty renderPipeline = graphicsManager.FindProperty("m_CustomRenderPipeline");
        renderPipeline.objectReferenceValue = null;

        SerializedProperty transparencySortMode = graphicsManager.FindProperty("m_TransparencySortMode");
        transparencySortMode.enumValueIndex = 0;

        SerializedProperty transparencySortAxis = graphicsManager.FindProperty("m_TransparencySortAxis");
        transparencySortAxis.vector3Value = Vector3.forward;

        SerializedProperty defaultRenderingPath = graphicsManager.FindProperty("m_DefaultRenderingPath");
        defaultRenderingPath.intValue = 1;

        SerializedProperty defaultMobileRenderingPath = graphicsManager.FindProperty("m_DefaultMobileRenderingPath");
        defaultMobileRenderingPath.intValue = 1;

        SerializedProperty tierSettings = graphicsManager.FindProperty("m_TierSettings");
        tierSettings.ClearArray();
        tierSettings.arraySize = 0;

        #if ENV_SET_LIGHTMAP
        SerializedProperty lightmapStripping = graphicsManager.FindProperty("m_LightmapStripping");
        lightmapStripping.enumValueIndex = 1;

        SerializedProperty instancingStripping = graphicsManager.FindProperty("m_InstancingStripping");
        instancingStripping.enumValueIndex = 2;

        SerializedProperty lightmapKeepPlain = graphicsManager.FindProperty("m_LightmapKeepPlain");
        lightmapKeepPlain.boolValue = true;

        SerializedProperty lightmapKeepDirCombined = graphicsManager.FindProperty("m_LightmapKeepDirCombined");
        lightmapKeepDirCombined.boolValue = true;

        SerializedProperty lightmapKeepDynamicPlain = graphicsManager.FindProperty("m_LightmapKeepDynamicPlain");
        lightmapKeepDynamicPlain.boolValue = true;

        SerializedProperty lightmapKeepDynamicDirCombined = graphicsManager.FindProperty("m_LightmapKeepDynamicDirCombined");
        lightmapKeepDynamicDirCombined.boolValue = true;

        SerializedProperty lightmapKeepShadowMask = graphicsManager.FindProperty("m_LightmapKeepShadowMask");
        lightmapKeepShadowMask.boolValue = true;

        SerializedProperty lightmapKeepSubtractive = graphicsManager.FindProperty("m_LightmapKeepSubtractive");
        lightmapKeepSubtractive.boolValue = true;
        #endif

        SerializedProperty albedoSwatchInfos = graphicsManager.FindProperty("m_AlbedoSwatchInfos");
        albedoSwatchInfos.ClearArray();
        albedoSwatchInfos.arraySize = 0;

        SerializedProperty lightsUseLinearIntensity = graphicsManager.FindProperty("m_LightsUseLinearIntensity");
        lightsUseLinearIntensity.boolValue = true;

        SerializedProperty lightsUseColorTemperature = graphicsManager.FindProperty("m_LightsUseColorTemperature");
        lightsUseColorTemperature.boolValue = true;

        graphicsManager.ApplyModifiedProperties();
    }
    public override void OnInspectorGUI()
    {
        this.serializedObject.Update();

        GUI.enabled = false;
        EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
        GUI.enabled = true;

#if UNITY_STANDALONE
#if UNITY_5_6_OR_NEWER
#if NET_2_0
        CommSerial socket = (CommSerial)target;
        GUI.enabled = !socket.IsOpen;

#if UNITY_EDITOR_WIN
        EditorGUILayout.LabelField(string.Format("Port Name: {0}", socket.device.name));
#elif UNITY_EDITOR_OSX
        EditorGUILayout.LabelField(string.Format("Port Name: {0}", socket.device.address));
#endif
        EditorGUILayout.BeginHorizontal();
        int      index = -1;
        string[] list  = new string[socket.foundDevices.Count];
        for (int i = 0; i < list.Length; i++)
        {
            list[i] = socket.foundDevices[i].name;
            if (deviceName.stringValue.Equals(socket.foundDevices[i].name))
            {
                index = i;
            }
        }
        int newIndex = EditorGUILayout.Popup(" ", index, list);
        if (newIndex != index)
        {
            CommDevice newDevice = socket.foundDevices[newIndex];
            deviceName.stringValue    = newDevice.name;
            deviceAddress.stringValue = newDevice.address;
            deviceArgs.ClearArray();
            deviceArgs.arraySize = newDevice.args.Count;
            for (int i = 0; i < newDevice.args.Count; i++)
            {
                SerializedProperty arg = deviceArgs.GetArrayElementAtIndex(i);
                arg.stringValue = newDevice.args[i];
            }
        }

        if (GUILayout.Button("Search", GUILayout.Width(60f)) == true)
        {
            socket.StartSearch();
        }
        EditorGUILayout.EndHorizontal();

        GUI.enabled = true;
#else
        EditorGUILayout.HelpBox("You must set as '.Net 2.0' for API Compatibility Level in PlayerSetting.", MessageType.Error);
#endif
#else
        CommSerial socket = (CommSerial)target;
        GUI.enabled = !socket.IsOpen;

#if UNITY_EDITOR_WIN
        EditorGUILayout.LabelField(string.Format("Port Name: {0}", socket.device.name));
#elif UNITY_EDITOR_OSX
        EditorGUILayout.LabelField(string.Format("Port Name: {0}", socket.device.address));
#endif
        EditorGUILayout.BeginHorizontal();
        int      index = -1;
        string[] list  = new string[socket.foundDevices.Count];
        for (int i = 0; i < list.Length; i++)
        {
            list[i] = socket.foundDevices[i].name;
            if (deviceName.stringValue.Equals(socket.foundDevices[i].name))
            {
                index = i;
            }
        }
        int newIndex = EditorGUILayout.Popup(" ", index, list);
        if (newIndex != index)
        {
            CommDevice newDevice = socket.foundDevices[newIndex];
            deviceName.stringValue    = newDevice.name;
            deviceAddress.stringValue = newDevice.address;
            deviceArgs.ClearArray();
            deviceArgs.arraySize = newDevice.args.Count;
            for (int i = 0; i < newDevice.args.Count; i++)
            {
                SerializedProperty arg = deviceArgs.GetArrayElementAtIndex(i);
                arg.stringValue = newDevice.args[i];
            }
        }

        if (GUILayout.Button("Search", GUILayout.Width(60f)) == true)
        {
            socket.StartSearch();
        }
        EditorGUILayout.EndHorizontal();

        GUI.enabled = true;
#endif
#else
        EditorGUILayout.HelpBox("This component only can work on standalone platform(windows, osx, linux..)", MessageType.Error);
#endif

        EditorGUILayout.PropertyField(baudrate, new GUIContent("Baudrate"));
        EditorGUILayout.PropertyField(dtrReset, new GUIContent("DTR Reset"));

        foldout = EditorGUILayout.Foldout(foldout, "Events");
        if (foldout)
        {
            EditorGUILayout.PropertyField(OnOpen, new GUIContent("OnOpen"));
            EditorGUILayout.PropertyField(OnClose, new GUIContent("OnClose"));
            EditorGUILayout.PropertyField(OnOpenFailed, new GUIContent("OnOpenFailed"));
            EditorGUILayout.PropertyField(OnErrorClosed, new GUIContent("OnErrorClosed"));
            EditorGUILayout.PropertyField(OnStartSearch, new GUIContent("OnStartSearch"));
            EditorGUILayout.PropertyField(OnStopSearch, new GUIContent("OnStopSearch"));
        }

        this.serializedObject.ApplyModifiedProperties();
    }
Beispiel #15
0
        void SerilizeEvents(ModelImporter modelImporter, IList <AnimationEvent> events, int id)
        {
            //var clipAnimations = modelImporter.defaultClipAnimations;
            //var m_clip = clipAnimations[0];

            //m_clip.events = events.ToArray();
            //modelImporter.SaveAndReimport();
            //AssetDatabase.Refresh();

            //ModelImporter importer = modelImporter;
            //if (importer != null)
            //{
            //    List<ModelImporterClipAnimation> animList = new List<ModelImporterClipAnimation>();

            //    for (int i = 0; i < importer.clipAnimations.Length; i++)
            //    {
            //        animList.Add(AssgnEvent(importer.clipAnimations[i],events));
            //    }

            //    importer.clipAnimations = animList.ToArray();

            //}
            //SerializedObject serializedObject = new SerializedObject(importer);
            //serializedObject.ApplyModifiedProperties();
            //importer.SaveAndReimport();
            //AssetDatabase.Refresh();

            SerializedObject serializedObject = new SerializedObject(modelImporter);

            //RECORD避免第一次因版本差异序列化失败
            AssetDatabase.Refresh();

            if (modelImporter.clipAnimations == null || modelImporter.clipAnimations.Length == 0)
            {
                modelImporter.clipAnimations = modelImporter.defaultClipAnimations;
            }

            SerializedProperty clipAnimations = serializedObject.FindProperty("m_ClipAnimations");

            if (clipAnimations == null || clipAnimations.arraySize == 0)
            {
                MessageBox(string.Format($" m_ClipAnimations = null,clip:{modelImporter.assetPath} skillID: {id}"));
            }
            else
            {
                SerializedProperty m_clip   = clipAnimations.GetArrayElementAtIndex(0);
                SerializedProperty m_events = m_clip.FindPropertyRelative("events");
                if (modelImporter.clipAnimations.Length == 1)
                {
                    m_events.ClearArray();
                    foreach (AnimationEvent evt in events)
                    {
                        m_events.InsertArrayElementAtIndex(m_events.arraySize);
                        SetEvent(m_events, m_events.arraySize - 1, evt);
                    }

                    serializedObject.ApplyModifiedProperties();
                    modelImporter.SaveAndReimport();
                    AssetDatabase.Refresh();
                }
                else
                {
                    MessageBox(string.Format($" clipAnimations != 1,技能ID:{id}"));
                }
            }
        }
Beispiel #16
0
        private void DrawPrefabsInfoHeader(Rect rect)
        {
            var titleRect = new Rect(rect.x, rect.y, 100, EditorGUIUtility.singleLineHeight);

            EditorGUI.LabelField(titleRect, "信息列表");
            var createAllRect = new Rect(rect.x + rect.width - 3 * btnWidth, rect.y, btnWidth, EditorGUIUtility.singleLineHeight);

            if (GUI.Button(createAllRect, "clear"))
            {
                var confer = EditorUtility.DisplayDialog("温馨提示", "如需清除所有记录的信息,请按确认", "确认");
                if (confer)
                {
                    prefabInfosProp.ClearArray();
                }
            }
            createAllRect.x += btnWidth;
            if (GUI.Button(createAllRect, "record"))
            {
                if (Selection.instanceIDs != null)
                {
                    List <GameObject> prefabs = (target as PrefabGroupObj).prefabs;
                    foreach (var item in Selection.instanceIDs)
                    {
                        var obj = EditorUtility.InstanceIDToObject(item);
                        if (obj is GameObject)
                        {
                            var prefab = PrefabUtility.GetPrefabParent(obj);
                            if (prefab != null)
                            {
                                prefabInfosProp.InsertArrayElementAtIndex(prefabInfosProp.arraySize);
                                var prop = prefabInfosProp.GetArrayElementAtIndex(prefabInfosProp.arraySize - 1);
                                UpdateOneInfo(prop, obj as GameObject, prefab as GameObject);

                                if (!prefabs.Contains(prefab as GameObject))
                                {
                                    prefabs.Add(prefab as GameObject);
                                    prefabsProp.InsertArrayElementAtIndex(prefabsProp.arraySize);
                                    prefabsProp.GetArrayElementAtIndex(prefabsProp.arraySize - 1).objectReferenceValue = prefab;
                                }
                            }
                        }
                    }
                    EditorUtility.SetDirty(target);
                }
            }
            createAllRect.x += btnWidth;
            if (GUI.Button(createAllRect, "load"))
            {
                var parent = new GameObject(target.name).GetComponent <Transform>();
                List <GameObject> prefabs = (target as PrefabGroupObj).prefabs;
                for (int i = 0; i < prefabInfosProp.arraySize; i++)
                {
                    var prop = prefabInfosProp.GetArrayElementAtIndex(i);

                    var instenceNameProp = prop.FindPropertyRelative("instenceName");
                    var prefabNameProp   = prop.FindPropertyRelative("prefabName");
                    var positionProp     = prop.FindPropertyRelative("position");
                    var rotationProp     = prop.FindPropertyRelative("rotation");
                    var sizeProp         = prop.FindPropertyRelative("size");

                    var prefab = prefabs.Find(x => x.name == prefabNameProp.stringValue);
                    if (prefab != null)
                    {
                        var instence = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                        instence.transform.SetParent(parent, false);
                        instence.name = instenceNameProp.stringValue;
                        instence.transform.position   = positionProp.vector3Value;
                        instence.transform.rotation   = rotationProp.quaternionValue;
                        instence.transform.localScale = sizeProp.vector3Value;
                    }
                }
            }
        }
Beispiel #17
0
 public void RemoveAllElements()
 {
     _ClipList.ClearArray();
 }
Beispiel #18
0
        private void _refreshData()
        {
            _queues = this.serializedObject.FindProperty("Queues");

            _playOnAwake = this.serializedObject.FindProperty("playOnAwake");
            _title       = this.serializedObject.FindProperty("title");
            _onFinish    = base.serializedObject.FindProperty("onFinish");

            _list_queues = new ReorderableList(this.serializedObject, _queues, true, true, true, true);
            _list_queues.drawElementCallback = (rect, index, isActive, isFocus) =>
            {
                rect.height = EditorGUIUtility.singleLineHeight;
                rect.y     += 2;
                SerializedProperty itemData       = _queues.GetArrayElementAtIndex(index);
                SerializedProperty itemData_Anis  = itemData.FindPropertyRelative("UI_Anis");
                SerializedProperty itemData_Delay = itemData.FindPropertyRelative("DelayAfter");
                if (itemData_Anis.arraySize > 0)
                {
                    for (var i = 0; i < itemData_Anis.arraySize; i++)
                    {
                        var rect_item = rect;
                        rect_item.y += i * (EditorGUIUtility.singleLineHeight + 2);
                        var ani_item = itemData_Anis.GetArrayElementAtIndex(i);
                        var ani_obj  = ani_item.FindPropertyRelative("UI_Ani");
                        var ready    = ani_item.FindPropertyRelative("ReadyOnQueueStart");

                        var rect_obj = rect_item;
                        rect_obj.width -= 80;
                        ani_obj.objectReferenceValue = EditorGUI.ObjectField(rect_obj, ani_obj.objectReferenceValue, typeof(UIAnimationBase), true);

                        var rect_ready = rect_item;
                        rect_ready.x    += rect_obj.width + 4;
                        rect_ready.width = 55;
                        ready.boolValue  = EditorGUI.ToggleLeft(rect_ready, new GUIContent("Ready", "If ready, The target of this animation will be set to the origin value at the beginning of the queue"), ready.boolValue);

                        var rect_del = rect_item;
                        rect_del.x    += rect_obj.width + 4 + rect_ready.width + 2;
                        rect_del.width = 19;
                        if (GUI.Button(rect_del, new GUIContent("×", "Delete")))
                        {
                            itemData_Anis.DeleteArrayElementAtIndex(i);
                        }
                    }
                }
                //add btn
                var rect_btn_add = rect;
                rect_btn_add.y    += (itemData_Anis.arraySize) * (EditorGUIUtility.singleLineHeight + 2);
                rect_btn_add.width = 80;
                if (GUI.Button(rect_btn_add, "Add"))
                {
                    var __index = itemData_Anis.arraySize;
                    itemData_Anis.InsertArrayElementAtIndex(__index);
                    var this_data = itemData_Anis.GetArrayElementAtIndex(__index);
                    this_data.FindPropertyRelative("UI_Ani").objectReferenceValue = null;
                    this_data.FindPropertyRelative("ReadyOnQueueStart").boolValue = false;
                }
                var rect_delay = rect;
                rect_delay.y += (itemData_Anis.arraySize + 1) * (EditorGUIUtility.singleLineHeight + 2);
                itemData_Delay.floatValue = EditorGUI.FloatField(rect_delay, new GUIContent("Delay After:"), itemData_Delay.floatValue);
            };
            _list_queues.elementHeightCallback = (index) =>
            {
                var count = _queues.GetArrayElementAtIndex(index).FindPropertyRelative("UI_Anis").arraySize;
                return((EditorGUIUtility.singleLineHeight + 2) * (count + 2) + 5);
            };
            _list_queues.onAddCallback = (list) =>
            {
                if (list.serializedProperty != null)
                {
                    list.serializedProperty.arraySize++;
                    list.index = list.serializedProperty.arraySize - 1;

                    SerializedProperty itemData   = list.serializedProperty.GetArrayElementAtIndex(list.index);
                    SerializedProperty item_anis  = itemData.FindPropertyRelative("UI_Anis");
                    SerializedProperty item_delay = itemData.FindPropertyRelative("DelayAfter");
                    item_anis.ClearArray();
                    item_delay.floatValue = 0;
                }
                else
                {
                    ReorderableList.defaultBehaviours.DoAddButton(list);
                }
            };
            _list_queues.drawHeaderCallback = rect =>
            {
                EditorGUI.LabelField(rect, "UI Animation Queue");
            };
            _refresh_data = true;
        }
Beispiel #19
0
    void DisplayAddMainArea()
    {
        // only run this once
        if (!hasLooped)
        {
            //clear fields
            if (id != null)
            {
                GUI.SetNextControlName("Name");
                id.ClearArray();
                GUI.FocusControl("Name");
                requirementsArray.ClearArray();
                itemPopUpIndex.Clear();
            }

            hasLooped = true;
        }

        scrollPositionMain = EditorGUILayout.BeginScrollView(scrollPositionMain);

        var itemsArray = itemDbList.GetArrayElementAtIndex(itemDbList.arraySize - 1);

        id                = itemsArray.FindPropertyRelative("id");
        clicks            = itemsArray.FindPropertyRelative("clicks");
        craftTime         = itemsArray.FindPropertyRelative("craftTime");
        sellAmount        = itemsArray.FindPropertyRelative("sellAmount");
        requirementsArray = itemsArray.FindPropertyRelative("requirements");

        EditorGUILayout.LabelField("Name", EditorStyles.boldLabel);
        id.stringValue = EditorGUILayout.TextField(id.stringValue);

        EditorGUILayout.LabelField("Clicks", EditorStyles.boldLabel);
        clicks.intValue = EditorGUILayout.IntField(clicks.intValue);

        EditorGUILayout.LabelField("Craft Time", EditorStyles.boldLabel);
        craftTime.intValue = EditorGUILayout.IntField(craftTime.intValue);

        EditorGUILayout.LabelField("Sell Amount", EditorStyles.boldLabel);
        sellAmount.intValue = EditorGUILayout.IntField(sellAmount.intValue);

        if (itemDb.Count > 1)
        {
            GUI.color = colorGreen;
            if (GUILayout.Button("Add Requirement"))
            {
                requirementsArray.InsertArrayElementAtIndex(requirementsArray.arraySize);
                itemPopUpIndex.Add(itemPopUpIndex.Count);
            }
        }

        for (var i = 0; i < requirementsArray.arraySize; i++)
        {
            requirementName   = requirementsArray.GetArrayElementAtIndex(i).FindPropertyRelative("item");
            requirementAmount = requirementsArray.GetArrayElementAtIndex(i).FindPropertyRelative("amount");

            EditorGUILayout.LabelField("Requirement " + (i + 1), EditorStyles.boldLabel);
            GUI.color                   = colorDefault;
            itemPopUpIndex[i]           = EditorGUILayout.Popup("Item:", itemPopUpIndex[i], GetItemPopUpList());
            requirementName.stringValue = IndexToString(itemPopUpIndex[i]);
            requirementAmount.intValue  = EditorGUILayout.IntField("Amount", requirementAmount.intValue);

            GUI.color = colorRed;
            if (GUILayout.Button("Remove Requirement"))
            {
                requirementsArray.DeleteArrayElementAtIndex(i);
            }
        }

        EditorGUILayout.Space();

        GUI.color = colorDefault;
        if (GUILayout.Button("Create", GUILayout.Width(100)))
        {
            // data validation
            if (id.stringValue.IsNullOrEmpty())
            {
                EditorUtility.DisplayDialog("Error", "Name cannot be empty!", "Ok");
                return;
            }

            for (var i = 0; i < requirementsArray.arraySize; i++)
            {
                // data validation
                if (requirementsArray.GetArrayElementAtIndex(i).FindPropertyRelative("amount").intValue == 0)
                {
                    EditorUtility.DisplayDialog("Error", "Amount cannot be zero!", "Ok");
                    return;
                }
            }

            AddItemToPopUpList(id.stringValue);
            itemDb.Item(itemDb.Count - 1).Id           = id.stringValue;
            itemDb.Item(itemDb.Count - 1).Clicks       = clicks.intValue;
            itemDb.Item(itemDb.Count - 1).CraftTime    = craftTime.intValue;
            itemDb.Item(itemDb.Count - 1).SellAmount   = sellAmount.intValue;
            itemDb.Item(itemDb.Count - 1).Requirements = SerializedArrayToList(requirementsArray);

            //clear fields
            GUI.SetNextControlName("Name");
            id.ClearArray();
            GUI.FocusControl("Name");
            requirementsArray.ClearArray();
            itemPopUpIndex.Clear();

            RefreshDatabase();
            EditorUtility.SetDirty(itemDb);
            hasLooped = false;
            state     = State.BLANK;
        }

        GUI.color = colorDefault;
        if (GUILayout.Button("Cancel", GUILayout.Width(100)))
        {
            //clear fields
            GUI.SetNextControlName("Name");
            id.ClearArray();
            GUI.FocusControl("Name");
            requirementsArray.ClearArray();
            itemPopUpIndex.Clear();

            itemDb.RemoveAt(itemDb.Count - 1);

            hasLooped = false;
            state     = State.BLANK;
        }

        EditorGUILayout.EndScrollView();
    }
        private void DrawToolButtons()
        {
            var btnStyle   = EditorStyles.miniButton;
            var widthSytle = GUILayout.Width(20);

            switch (EnumIndexToLoadType(defultTypeProp.enumValueIndex))
            {
            case LoadType.Prefab:
                using (var hor = new EditorGUILayout.HorizontalScope(widthSytle))
                {
                    if (GUILayout.Button(new GUIContent("%", "移除重复"), btnStyle))
                    {
                        RemoveBundlesDouble(prefabsProp);
                        RemoveBridgesDouble(bridgesProp);
                    }
                    if (GUILayout.Button(new GUIContent("*", "快速更新"), btnStyle))
                    {
                        prefabsProp.ClearArray();
                        bridgesProp.ClearArray();
                        EditorApplication.delayCall += QuickUpdateFromGraph;
                    }
                    if (GUILayout.Button(new GUIContent("!", "排序"), btnStyle))
                    {
                        SortAllBundles(prefabsProp);
                    }
                    if (GUILayout.Button(new GUIContent("o", "批量加载"), btnStyle))
                    {
                        GroupLoadPrefabs(prefabsProp);
                    }
                    if (GUILayout.Button(new GUIContent("c", "批量关闭"), btnStyle))
                    {
                        CloseAllCreated(prefabsProp);
                    }
                }
                break;

            case LoadType.Bundle:
                using (var hor = new EditorGUILayout.HorizontalScope(widthSytle))
                {
                    resetMenuProp.boolValue = GUILayout.Toggle(resetMenuProp.boolValue, new GUIContent("r", "重设菜单"), btnStyle);

                    if (GUILayout.Button(new GUIContent("%", "移除重复"), btnStyle))
                    {
                        RemoveBundlesDouble(bundlesProp);
                        RemoveBridgesDouble(bridgesProp);
                    }
                    if (GUILayout.Button(new GUIContent("*", "快速更新"), btnStyle))
                    {
                        QuickUpdateBundles();
                        bundlesProp.ClearArray();
                        bridgesProp.ClearArray();
                        EditorApplication.delayCall += QuickUpdateFromGraph;
                    }
                    if (GUILayout.Button(new GUIContent("!", "排序"), btnStyle))
                    {
                        SortAllBundles(bundlesProp);
                    }
                    if (GUILayout.Button(new GUIContent("o", "批量加载"), btnStyle))
                    {
                        GroupLoadPrefabs(bundlesProp);
                    }
                    if (GUILayout.Button(new GUIContent("c", "批量关闭"), btnStyle))
                    {
                        CloseAllCreated(bundlesProp);
                    }
                }
                break;

            default:
                break;
            }
        }
Beispiel #21
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            EditorGUILayout.PropertyField(m_UIShowTriggerMode);
            EditorGUILayout.PropertyField(m_UIHideTriggerMode);
            EditorGUILayout.Space();

            var optionsArray = m_OptionDataList.FindPropertyRelative("m_Options");
            var arraySize    = optionsArray.arraySize;

            //Max Amount of EnumPopup value (display as int array)
            if (arraySize > 32)
            {
                EditorGUILayout.HelpBox("Max amount of elements to display as Popup is 32", MessageType.Info);
                EditorGUILayout.PropertyField(m_SelectedIndexes);
            }
            else
            {
                //Convert int array to mask
                int maskValue = 0;
                for (int i = 0; i < m_SelectedIndexes.arraySize; i++)
                {
                    maskValue |= (int)Mathf.Pow(2, m_SelectedIndexes.GetArrayElementAtIndex(i).intValue);
                }

                //Find the "Everything" value (when all options is selected)
                int everythingValue = 0;
                for (int i = 0; i < arraySize; i++)
                {
                    everythingValue |= (int)Mathf.Pow(2, i);
                }

                //Convert to unity everything (-1) if needed
                if (maskValue == everythingValue)
                {
                    maskValue = -1;
                }

                //Get options DisplayName
                List <string> displayedOptions = new List <string>();
                for (int i = 0; i < optionsArray.arraySize; i++)
                {
                    displayedOptions.Add(optionsArray.GetArrayElementAtIndex(i).FindPropertyRelative("m_Text").stringValue);
                }

                if (displayedOptions.Count > 0)
                {
                    var newMaskValue = EditorGUILayout.MaskField(m_SelectedIndexes.displayName, maskValue, displayedOptions.ToArray());

                    //Convert newMaskValue to unity everything (-1) if needed
                    if (newMaskValue == everythingValue)
                    {
                        newMaskValue = -1;
                    }

                    //Convert mask to int array
                    if (maskValue != newMaskValue)
                    {
                        List <int> indexArray = new List <int>();
                        for (int i = 0; i < Mathf.Max(optionsArray.arraySize, 32); i++)
                        {
                            var currentCheckingBitmask = (int)Mathf.Pow(2, i);
                            if ((newMaskValue & currentCheckingBitmask) == currentCheckingBitmask)
                            {
                                indexArray.Add(i);
                            }
                        }
                        //Recreate array with selected indexes
                        m_SelectedIndexes.ClearArray();
                        for (int i = 0; i < indexArray.Count; i++)
                        {
                            var selectedIndex = indexArray[i];
                            m_SelectedIndexes.InsertArrayElementAtIndex(i);
                            m_SelectedIndexes.GetArrayElementAtIndex(i).intValue = selectedIndex;
                        }
                    }
                }
            }
            EditorGUILayout.Space();
            EditorGUILayout.PropertyField(m_CustomFramePrefabAddress, new GUIContent("Custom Address"));
            EditorGUILayout.Space();
            EditorGUILayout.PropertyField(m_SpinnerMode);

            EditorGUI.indentLevel++;
            if (m_SpinnerMode.enumValueIndex != 1)
            {
                LayoutStyle_PropertyField(m_DropdownOffset);
                LayoutStyle_PropertyField(m_DropdownExpandPivot);
                LayoutStyle_PropertyField(m_DropdownFramePivot);
                LayoutStyle_PropertyField(m_DropdownFramePreferredSize);
            }
            if (m_SpinnerMode.enumValueIndex != 2)
            {
                LayoutStyle_PropertyField(m_OpenDialogAsync);
            }
            EditorGUI.indentLevel--;

            EditorGUILayout.Space();
            DrawFoldoutComponents(ComponentsSection);

            EditorGUILayout.Space();
            OptionsSection();

            EditorGUILayout.Space();
            EditorGUILayout.PropertyField(OnItemsSelected);
            EditorGUILayout.PropertyField(OnCancelCallback);

            EditorGUILayout.Space();
            DrawStyleGUIFolder();

            serializedObject.ApplyModifiedProperties();
        }
Beispiel #22
0
 private void _clearSer()
 {
     _languageNamesSer.ClearArray();
     serializedObject.ApplyModifiedProperties();
     serializedObject.Update();
 }
Beispiel #23
0
        public override void OnInspectorGUI()
        {
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.LabelField("Data", EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Collection:");
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(targetCollection);
            if (EditorGUI.EndChangeCheck())
            {
                if (columns.arraySize > 0 && EditorUtility.DisplayDialog("You changed the target collection", "Your columns will likely become invalid.\nClear the selected columns?", "Clear", "Do not clear"))
                {
                    columns.ClearArray();
                }
            }
            EditorGUILayout.Space();
            EditorGUILayout.Space();
            if (table.targetCollection.IsDefined)
            {
                reorderableList.DoLayoutList();
                GUI.enabled = true;
            }

            List <TableColumnInfo> tableColumnInfos = (List <TableColumnInfo>)columns.GetTargetObjectOfProperty();

            if (tableColumnInfos.Count > 0 && tableColumnInfos.All(tci => !tci.autoWidth))
            {
                DrawWarning("No auto-width column.");
            }
            if (tableColumnInfos.Count > 0 && tableColumnInfos.Sum(tci => tci.autoWidth ? 0f : tci.AbsoluteWidth) > table.GetAvailableWidth())
            {
                DrawWarning("Columns don't fit in table's RectTransform.");
            }

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PropertyField(rowDeleteButtons, new GUIContent("\"Delete\" Buttons"));
            if (rowDeleteButtons.boolValue)
            {
                EditorGUIUtility.labelWidth = EditorGUIUtility.fieldWidth = 40f;
                EditorGUILayout.PropertyField(deleteColumnWidth, new GUIContent("Width"), GUILayout.Width(80f));
                EditorGUIUtility.labelWidth = EditorGUIUtility.fieldWidth = -1f;
                TableColumnInfoDrawer.DrawCellStyleButton(
                    EditorGUILayout.GetControlRect(false, GUILayout.Width(20f)),
                    deleteCellStyle,
                    table.deleteCellPrefab,
                    string.Format("{0}_Delete_Button_Style", serializedObject.targetObject.name),
                    table,
                    table.deleteCellStyleTemplate);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PropertyField(rowAddButton, new GUIContent("\"Add\" Button"));
            if (rowAddButton.boolValue)
            {
                TableColumnInfoDrawer.DrawCellStyleButton(
                    EditorGUILayout.GetControlRect(false, GUILayout.Width(20f)),
                    addCellStyle,
                    table.addCellPrefab,
                    string.Format("{0}_Add_Button_Style", serializedObject.targetObject.name),
                    table,
                    table.addCellStyleTemplate);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Appearance", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(rowsColorMode, new GUIContent("Row Colors"));
            EditorGUI.indentLevel++;
            if (table.rowsColorMode == Table.RowsColorMode.Plain)
            {
                EditorGUILayout.PropertyField(bgColor, new GUIContent("Color"));
            }
            else
            {
                EditorGUILayout.PropertyField(bgColor, new GUIContent("Odd Rows"));
                EditorGUILayout.PropertyField(altBgColor, new GUIContent("Even Rows"));
            }
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            EditorGUILayout.PropertyField(selectableRows, new GUIContent("Selectable Lines"));
            if (selectableRows.boolValue)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(selectedBgColor, new GUIContent("Selected Color"));
                EditorGUI.indentLevel--;
            }
            EditorGUILayout.Space();
            bool oldOutline = lineColor.colorValue != Color.clear;
            bool newOutline = EditorGUILayout.Toggle(new GUIContent("Outline"), oldOutline);

            if (oldOutline && !newOutline)
            {
                lineColor.colorValue = Color.clear;
                spacing.floatValue   = 0f;
            }
            else if (!oldOutline && newOutline)
            {
                lineColor.colorValue = Color.black;
                spacing.floatValue   = -1f;
            }
            if (newOutline)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(lineColor, new GUIContent("Color"));
                EditorGUILayout.PropertyField(spacing);
                EditorGUI.indentLevel--;
                EditorGUILayout.Space();
            }
            EditorGUILayout.Space();

            EditorGUILayout.LabelField("Headers");
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(titleBGColor, new GUIContent("BG Color"));
            EditorGUILayout.PropertyField(titleFont, new GUIContent("Font"));
            EditorGUILayout.PropertyField(titleFontStyle, new GUIContent("Font Style"));
            EditorGUILayout.PropertyField(titleFontSize, new GUIContent("Font Size"));
            EditorGUILayout.PropertyField(titleFontColor, new GUIContent("Font Color"));
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();

            EditorGUILayout.PropertyField(rowHeight, new GUIContent("Default Row Height"));
            bool isScrollable = table.IsScrollable;

            if (EditorGUILayout.Toggle("Scrollable", isScrollable) != isScrollable)
            {
                table.MakeScrollable(!isScrollable);
            }

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Performance", EditorStyles.boldLabel);
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("At Runtime:");
            EditorGUI.indentLevel++;

            EditorGUILayout.LabelField("Update");
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(updateCellStyleAtRuntime, new GUIContent("Cell Style", "Updates the cells style at runtime. Enable if you plan to modify these styles at runtime."));
            EditorGUILayout.PropertyField(updateCellContentAtRuntime, new GUIContent("Cell Content", "Updates the cells content at runtime from the target collection. Enable if the collection's elements might be modified outside of the table."));
            EditorGUI.indentLevel--;

            EditorGUILayout.Space();
            EditorGUI.indentLevel--;
            EditorGUILayout.LabelField("In Edit Mode:");
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(limitRowsInEditMode, new GUIContent("Limit Rows", "Limit the number of rows to display in edit mode for previewing the table. This is important to avoid slowing down the editor when a large table is displayed."));
            if (limitRowsInEditMode.boolValue)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(nbRowsInEditMode, new GUIContent("Limit", "The maximum number of rows to display in edit mode for previewing the table."));
                EditorGUILayout.PropertyField(preinstantiateRowsOverLimit, new GUIContent("Preinstantiate all", "If true, all rows will be instantiated in edit mode but inactive. This will make the scene bigger but will be faster to start at runtime. If false, only rows below limit will be pre-instantiated."));
                EditorGUI.indentLevel--;
            }
            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
            serializedObject.ApplyModifiedProperties();
        }
Beispiel #24
0
        public static void SetValue(this SerializedProperty p, object value)
        {
            switch (p.propertyType)
            {
            case SerializedPropertyType.AnimationCurve:
                p.animationCurveValue = value as AnimationCurve;
                break;

            case SerializedPropertyType.ArraySize:
                //TODO: erm
                p.intValue = (int)value;
                break;

            case SerializedPropertyType.Boolean:
                p.boolValue = (bool)value;
                break;

            case SerializedPropertyType.Bounds:
                p.boundsValue = (Bounds)value;
                break;

            case SerializedPropertyType.Character:
                p.stringValue = (string)value;     //TODO: might be bullshit
                break;

            case SerializedPropertyType.Color:
                p.colorValue = (Color)value;
                break;

            case SerializedPropertyType.Enum:
                p.enumValueIndex = (int)value;
                break;

            case SerializedPropertyType.Float:
                p.floatValue = (float)value;
                break;

            case SerializedPropertyType.Generic:     //(arrays)
                if (p.isArray)
                {
                    //var size = p.arraySize;
                    //var resetPath = p.propertyPath;
                    var values = (object[])value;

                    /*
                     * for(int i = 0; i < p.arraySize; ++i)
                     * {
                     *  Debug.Log(i + ": " + p.GetArrayElementAtIndex(i).GetValue());
                     * }
                     */
                    p.ClearArray();
                    for (int i = 0; i < values.Length; ++i)
                    {
                        p.InsertArrayElementAtIndex(i);
                        //Debug.Log(i + ": " + pv.GetArrayElementAtIndex(i).GetValue());
                        p.GetArrayElementAtIndex(i).SetValue(values[i]);
                    }

                    //p.FindPropertyRelative(resetPath);
                }
                else
                {
                    //p.stringValue = (string)value;
                }
                break;

            case SerializedPropertyType.Gradient:
                //TODO: erm
                break;

            case SerializedPropertyType.Integer:
                p.intValue = (int)value;
                break;

            case SerializedPropertyType.LayerMask:
                p.intValue = (int)value;
                break;

            case SerializedPropertyType.ObjectReference:
                p.objectReferenceValue = value as Object;     //TODO: what about non-UnityEngine objects?
                break;

            case SerializedPropertyType.Quaternion:
                p.quaternionValue = (Quaternion)value;
                break;

            case SerializedPropertyType.Rect:
                p.rectValue = (Rect)value;
                break;

            case SerializedPropertyType.String:
                p.stringValue = (string)value;
                break;

            case SerializedPropertyType.Vector2:
                p.vector2Value = (Vector2)value;
                break;

            case SerializedPropertyType.Vector3:
                p.vector3Value = (Vector3)value;
                break;

            case SerializedPropertyType.Vector4:
                p.vector4Value = (Vector4)value;
                break;

            default:
                break;
            }
        }
Beispiel #25
0
 /// <summary>
 /// 設定を全てクリアします。
 /// </summary>
 public void Clear()
 {
     axesProperty.ClearArray();
     serializedObject.ApplyModifiedProperties();
 }
        public static void RestoreFromJson(this SerializedProperty property, ref JsonParser parser)
        {
            var isString = property.propertyType == SerializedPropertyType.String;

            if (property.isArray && !isString)
            {
                property.ClearArray();
                parser.ParseToken('[');
                while (!parser.ParseToken(']') && !parser.isAtEnd)
                {
                    var index = property.arraySize;
                    property.InsertArrayElementAtIndex(index);
                    var elementProperty = property.GetArrayElementAtIndex(index);
                    RestoreFromJson(elementProperty, ref parser);
                    parser.ParseToken(',');
                }
            }
            else if (property.hasChildren && !isString)
            {
                parser.ParseToken('{');
                while (!parser.ParseToken('}') && !parser.isAtEnd)
                {
                    parser.ParseStringValue(out var propertyName);
                    parser.ParseToken(':');

                    var childProperty = property.FindPropertyRelative(propertyName.ToString());
                    if (childProperty == null)
                    {
                        throw new ArgumentException($"Cannot find property '{propertyName}' in {property}", nameof(property));
                    }

                    RestoreFromJson(childProperty, ref parser);
                    parser.ParseToken(',');
                }
            }
            else
            {
                switch (property.propertyType)
                {
                case SerializedPropertyType.Float:
                {
                    parser.ParseNumber(out var num);
                    property.floatValue = (float)num.ToDouble();
                    break;
                }

                case SerializedPropertyType.String:
                {
                    parser.ParseStringValue(out var str);
                    property.stringValue = str.ToString();
                    break;
                }

                case SerializedPropertyType.Boolean:
                {
                    parser.ParseBooleanValue(out var b);
                    property.boolValue = b.ToBoolean();
                    break;
                }

                case SerializedPropertyType.Enum:
                case SerializedPropertyType.Integer:
                {
                    parser.ParseNumber(out var num);
                    property.intValue = (int)num.ToInteger();
                    break;
                }

                default:
                    throw new NotImplementedException(
                              $"Restoring property value of type {property.propertyType} (property: {property})");
                }
            }
        }
Beispiel #27
0
        public override void OnInspectorGUI()
        {
            float usableWidth = Screen.width - 64f;

            serializedObject.Update();
            int       oldGridSize = (int)Mathf.Sqrt(colors.arraySize);
            int       targetCount = gridSize.intValue * gridSize.intValue;
            int       i;
            string    assetPath = AssetDatabase.GetAssetPath(serializedObject.targetObject);
            Texture2D tex       = null;

            if (oldGridSize != gridSize.intValue)
            {
                int oldArraySize     = colors.arraySize;
                int gridSizeDelta    = gridSize.intValue - oldGridSize;
                int arrayLengthDelta = targetCount - colors.arraySize;
                if (gridSizeDelta > 0)
                {
                    for (i = 0; i < targetCount; i++)
                    {
                        int y = i / gridSize.intValue;
                        int x = i % gridSize.intValue;
                        if (y > oldGridSize - 1 || x > oldGridSize - 1)
                        {
                            colors.InsertArrayElementAtIndex(i);
                            colors.GetArrayElementAtIndex(i).colorValue = emptyColor.colorValue;
                        }
                    }
                }
                else if (arrayLengthDelta < 0)
                {
                    for (i = colors.arraySize - 1; i > 0; i--)
                    {
                        int y = i / oldGridSize;
                        int x = i % oldGridSize;
                        if (y > gridSize.intValue - 1 || x > gridSize.intValue - 1)
                        {
                            colors.DeleteArrayElementAtIndex(i);
                        }
                    }
                }
            }

            float cellSize = Mathf.Min(512f, usableWidth) / gridSize.intValue;

            i = 0;
            for (int y = 0; y < gridSize.intValue; y++)
            {
                EditorGUILayout.BeginHorizontal();
                for (int x = 0; x < gridSize.intValue; x++)
                {
                    SerializedProperty p = colors.GetArrayElementAtIndex(i);
                    p.colorValue = EditorGUILayout.ColorField(
                        GUIContent.none,
                        p.colorValue,
                        false,
                        true,
                        false,
                        GUILayout.Width(cellSize),
                        GUILayout.Height(cellSize)
                        );
                    i += 1;
                }
                EditorGUILayout.EndHorizontal();
            }

            GUILayout.Space(12f);

            _optionsOpen = EditorGUILayout.BeginFoldoutHeaderGroup(_optionsOpen, "Options");
            if (_optionsOpen)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(string.Format("Grid Size: {0} ({1} cells)",
                                                         gridSize.intValue,
                                                         colors.arraySize));
                GUI.enabled = gridSize.intValue > 1;
                if (GUILayout.Button("-"))
                {
                    gridSize.intValue -= 1;
                }
                GUI.enabled = gridSize.intValue < 12;  // an arbitrary choice because of the extra padding between cells
                if (GUILayout.Button("+"))
                {
                    gridSize.intValue += 1;
                }
                GUI.enabled = true;
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.PropertyField(emptyColor);
                EditorGUILayout.PropertyField(textureSize);

                GUILayout.Space(24f);
                if (GUILayout.Button("Clear Colors"))
                {
                    colors.ClearArray();
                    for (i = 0; i < targetCount; i++)
                    {
                        colors.InsertArrayElementAtIndex(i);
                        colors.GetArrayElementAtIndex(i).colorValue = emptyColor.colorValue;
                    }
                }

                GUILayout.Space(12f);
            }
            EditorGUILayout.EndFoldoutHeaderGroup();

            if (tex == null)
            {
                tex = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath);
            }

            GUILayout.Space(12f);
            if (GUILayout.Button(tex == null ? "Create Texture Asset" : "Update Texture Asset"))
            {
                if (assetPath != null)
                {
                    if (colors.arraySize == 0)
                    {
                        for (i = 0; i < targetCount; i++)
                        {
                            colors.InsertArrayElementAtIndex(i);
                            colors.GetArrayElementAtIndex(i).colorValue = emptyColor.colorValue;
                        }
                    }

                    if (tex == null)
                    {
                        tex            = new Texture2D(textureSize.intValue, textureSize.intValue);
                        tex.filterMode = FilterMode.Point;
                        AssetDatabase.AddObjectToAsset(tex, assetPath);
                    }
                    tex.name = serializedObject.targetObject.name + " Texture";
                    ((ScriptableColorPalette)serializedObject.targetObject).ApplyToTexture2D(tex);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.ImportAsset(assetPath);
                }
            }

            serializedObject.ApplyModifiedProperties();

            if (tex != null)
            {
                GUILayout.Space(12f);
                GUILayout.BeginVertical(GUILayout.Width(usableWidth));
                GUILayout.Space(usableWidth);
                GUILayout.EndVertical();
                GUI.DrawTexture(GUILayoutUtility.GetLastRect(), tex);

                GUILayout.Space(12f);
                GUILayout.Label(tex.name);
                GUILayout.Label(string.Format("{0}px by {1}px", tex.width, tex.height));

                GUILayout.Space(12f);
                if (GUILayout.Button("Show in Project"))
                {
                    EditorGUIUtility.PingObject(tex);
                }

                if (GUILayout.Button("Export PNG"))
                {
                    string savePath = EditorUtility.SaveFilePanel(
                        string.Format("Export {0} as PNG", tex.name),
                        "",
                        string.Format("{0}.png", tex.name),
                        "png"
                        );

                    if (savePath.Length != 0)
                    {
                        var pngData = tex.EncodeToPNG();
                        if (pngData != null)
                        {
                            File.WriteAllBytes(savePath, pngData);
                        }
                    }
                }
            }
        }
Beispiel #28
0
        protected override void DrawCustomEditor()
        {
            valid = true;
            base.DrawCustomEditor();
            if (Application.isPlaying)
            {
                EditorGUILayout.LabelField(new GUIContent("State Changes: ", "List of logged changes to GameState."));
                Rect tblRect = GUILayoutUtility.GetRect(0, Screen.width, 18, 18);
                GUI.Box(tblRect, string.Empty);
                EditorGUI.LabelField(new Rect(tblRect.x, tblRect.y, tblRect.width / 2, tblRect.height), "GameState");
                EditorGUI.LabelField(new Rect(tblRect.x + (tblRect.width / 2), tblRect.y, tblRect.width / 2, tblRect.height), "Time");

                int l = GameManager.Instance.accesses.Count;
                if (l > 0)
                {
                    var e = GameManager.Instance.accesses.First;
                    while (e != null)
                    {
                        Rect ar = GUILayoutUtility.GetRect(0, Screen.width, 18, 18);
                        GUI.Box(ar, string.Empty);
                        EditorGUI.LabelField(new Rect(ar.x, ar.y, ar.width / 2, ar.height), e.Value.name);
                        EditorGUI.LabelField(new Rect(ar.x + (ar.width / 2), ar.y, ar.width / 2, ar.height), e.Value.time.ToString());
                        if (EditorTools.InspectorClicked(ar, Event.current))
                        {
                            Debug.Log("stacktrace for ChangeState to " + e.Value.name + ":\n " + e.Value.stackTrace + " \n------\n");
                        }
                        e = e.Next;
                    }
                }
            }
            else
            {
                EditorGUI.BeginChangeCheck();
                GameManager.accessesLogged = EditorGUILayout.DelayedIntField(new GUIContent("Accesses Logged: ", "Maximun number of accesses to ChangeState that are logged."), GameManager.accessesLogged);
                if (EditorGUI.EndChangeCheck())
                {
                    SetEditorGState();
                }
            }
            GUILayout.Space(20);
            EditorGUILayout.PropertyField(gameManagerSceneNameProperty, new GUIContent("GM Scene"));
            GUILayout.Space(10);
            EditorGUILayout.PropertyField(loadModeProperty, new GUIContent("Load Mode"));

            GUILayout.Space(10);

            EditorGUILayout.PropertyField(buildInitAssetProperty, new GUIContent("Build Initial State"));
            EditorGUI.BeginChangeCheck();
            Rect r  = GUILayoutUtility.GetRect(0, Screen.width, 16, 16);
            Rect r1 = new Rect(r.x, r.y, r.width * 0.385f, r.height);
            Rect r2 = new Rect(r.x + (r.width * 0.385f), r.y, r.width * 0.615f, r.height);

            GameManager.useEditorGameStateAsset = GUI.Toggle(r1, GameManager.useEditorGameStateAsset, new GUIContent("Editor Initial State", "Initial State to load when the GameManager Starts on Editor (saved locally)"), GUI.skin.button);
            GameManager.editorGameStateAsset    = EditorGUI.ObjectField(r2, GameManager.editorGameStateAsset, typeof(GameStateAsset), false) as GameStateAsset;
            if (EditorGUI.EndChangeCheck())
            {
                SetEditorGState();
            }

            GUILayout.Space(10);

            gameStateAssetsList.DoLayoutList();
            if (!valid)
            {
                GUIStyle style = GUI.skin.box;
                style.wordWrap = true;
                GUIContent c = new GUIContent("Some of the selected scenes for this GameState are not added to the Build Settings.");
                float      h = style.CalcHeight(c, Screen.width);
                EditorGUILayout.HelpBox("Some of the selected scenes for this GameState are not added to the Build Settings.", MessageType.Error);

                GUILayout.Space(40 - h);
            }
            else
            {
                GUILayout.Space(40);
            }

            if (GUILayout.Button("Get GameStateAssets"))
            {
                string[] guids = AssetDatabase.FindAssets("t:GameStateAsset");

                gameStateAssetsProperty.ClearArray();
                foreach (string guid in guids)
                {
                    string         aPath = AssetDatabase.GUIDToAssetPath(guid);
                    GameStateAsset o     = AssetDatabase.LoadAssetAtPath <GameStateAsset>(aPath);
                    gameStateAssetsProperty.InsertArrayElementAtIndex(0);
                    gameStateAssetsProperty.GetArrayElementAtIndex(0).objectReferenceValue = o;
                }
                serializedObject.ApplyModifiedProperties();
                (target as GameManager).gameStateAssets.Sort(gameStatesComparer);
                serializedObject.ApplyModifiedProperties();
            }
            GUILayout.Space(20);
        }
Beispiel #29
0
        /// <summary>
        /// 绘制引用相关按钮
        /// </summary>
        private void DrawReferenceButton()
        {
            EditorGUILayout.BeginVertical();
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button(" + "))
            {
                var obj = new InspectorSerializObjct();
                obj._selectTypeIdx = 0;
                _list.Add(obj);
            }

            if (GUILayout.Button(" - "))
            {
                var cnt = _list.Count;
                if (cnt == 0)
                {
                    return;
                }

                _list.RemoveAt(cnt - 1);
            }

            if (GUILayout.Button("Save Reference"))
            {
                //重新写入到propertyList
                var cnt = _list.Count;
                if (_referenceList is null)
                {
                    return;
                }

                _referenceList.ClearArray();
                _referenceList.arraySize = cnt;

                InspectorSerializObjct sObj;
                for (int i = 0; i < cnt; i++)
                {
                    sObj = _list[i];
                    _referenceList.InsertArrayElementAtIndex(i);
                    var comp = _referenceList.GetArrayElementAtIndex(i);
                    var go   = comp.FindPropertyRelative("go");
                    var type = comp.FindPropertyRelative("type");
                    var name = comp.FindPropertyRelative("name");
                    go.objectReferenceValue = sObj._serializObject.GameObj;
                    type.stringValue        = sObj._serializObject.Type;
                    name.stringValue        = sObj._serializObject.Name;
                }
                //写入类名
                var className = serializedObject.FindProperty("_className");
                className.stringValue = _className;

                //Undo.RecordObject( target, "tar changed" );
                serializedObject.ApplyModifiedProperties();
            }

            if (GUILayout.Button("Clear Reference"))
            {
                _referenceList?.ClearArray();
                _list?.Clear();
                serializedObject.ApplyModifiedProperties();
            }

            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }
Beispiel #30
0
        public static void SetToDefault(this SerializedProperty property)
        {
            if (property.isArray)
            {
                property.ClearArray();
            }
            else if (property.hasChildren)
            {
                var end = property.GetEndProperty();
                property.NextVisible(true);

                while (!SerializedProperty.EqualContents(property, end))
                {
                    property.SetToDefault();
                    property.NextVisible(false);
                }
            }
            else
            {
                switch (property.propertyType)
                {
                case SerializedPropertyType.Generic: break;

                case SerializedPropertyType.Integer: property.intValue = default; break;

                case SerializedPropertyType.Boolean: property.boolValue = default; break;

                case SerializedPropertyType.Float: property.floatValue = default; break;

                case SerializedPropertyType.String: property.stringValue = string.Empty; break;

                case SerializedPropertyType.Color: property.colorValue = default; break;

                case SerializedPropertyType.ObjectReference: property.objectReferenceValue = default; break;

                case SerializedPropertyType.LayerMask: property.intValue = 0; break;

                case SerializedPropertyType.Enum: property.enumValueIndex = 0; break;

                case SerializedPropertyType.Vector2: property.vector2Value = default; break;

                case SerializedPropertyType.Vector3: property.vector3Value = default; break;

                case SerializedPropertyType.Vector4: property.vector4Value = default; break;

                case SerializedPropertyType.Rect: property.rectValue = default; break;

                case SerializedPropertyType.ArraySize: property.intValue = 0; break;

                case SerializedPropertyType.Character: property.intValue = default; break;

                case SerializedPropertyType.AnimationCurve: property.animationCurveValue = default; break;

                case SerializedPropertyType.Bounds: property.boundsValue = default; break;

                case SerializedPropertyType.Gradient: property.SetGradientValue(default); break;

                case SerializedPropertyType.Quaternion: property.quaternionValue = default; break;

                case SerializedPropertyType.ExposedReference: property.exposedReferenceValue = default; break;

                case SerializedPropertyType.FixedBufferSize: property.intValue = 0; break;

                case SerializedPropertyType.Vector2Int: property.vector2IntValue = default; break;

                case SerializedPropertyType.Vector3Int: property.vector3IntValue = default; break;

                case SerializedPropertyType.RectInt: property.rectIntValue = default; break;

                case SerializedPropertyType.BoundsInt: property.boundsIntValue = default; break;
                }
            }
        }