示例#1
0
        /// <summary>
        /// Updates the serialized objects and properties.
        /// </summary>
        private void RefreshSerializedSelection()
        {
            List <NavTile> navTiles;
            List <NavLink> navLinks;

            GetSelectedNavTiles(out navTiles, out navLinks);

            if (navTiles.Count == 0)
            {
                _serializedNavTileSelection = null;
                _serializedNavTileAreaIndex = null;
            }
            else
            {
                _serializedNavTileSelection = new SerializedObject(navTiles.ToArray());
                _serializedNavTileAreaIndex = _serializedNavTileSelection?.FindProperty("AreaIndex");
            }

            if (navLinks.Count == 0)
            {
                _serializedNavLinkSelection = null;
                _serializedNavLinkAreaIndex = null;
            }
            else
            {
                _serializedNavLinkSelection = new SerializedObject(navLinks.ToArray());
                _serializedNavLinkAreaIndex = _serializedNavLinkSelection?.FindProperty("AreaIndex");
            }
        }
示例#2
0
 private void addOrRemoveLocale()
 {
     newLocaleName = EditorGUILayout.TextField(new GUIContent("Name"), newLocaleName);
     if (GUILayout.Button("+"))
     {
         LocaleData         newLocale      = AssetCreator.Create <LocaleData>(newLocaleName, Strings.ResourcesRoot + settings.LocalesPath);
         SerializedProperty localizedItems = serializedLocales?.FindProperty("items");
         if (localizedItems?.arraySize > 0)
         {
             SerializedObject   newLocaleSerialized = new SerializedObject(newLocale);
             SerializedProperty newLocaleItems      = newLocaleSerialized.FindProperty("items");
             do
             {
                 newLocaleItems.arraySize++;
                 int index = newLocaleItems.arraySize - 1;
                 SerializedProperty currentKey      = newLocaleItems.GetArrayElementAtIndex(index).FindPropertyRelative("key");
                 string             currentKeyValue = localizedItems.GetArrayElementAtIndex(index).FindPropertyRelative("key").stringValue;
                 currentKey.stringValue = currentKeyValue;
             } while(newLocaleItems.arraySize != localizedItems.arraySize);
             newLocaleSerialized.ApplyModifiedProperties();
         }
         newLocaleName = string.Empty;
         // OnProjectChanged gets called as soon as the asset is created, so this has to be here instead.
         init();
     }
 }
示例#3
0
        public override void OnInspectorGUI()
        {
            var character = (Character)target;
            SerializedObject characterSerialized = new SerializedObject(character);

            GUILayout.Space(10f);
            GUILayout.Label("Main", GUIStyleUtils.GetStyle(GUIStyleType.NORMAL_HEADER));
            GUILayout.Space(10f);


            character.CharacterType = (PCharacterType)EditorGUILayout.EnumPopup(character.CharacterType);
            character.Name          = EditorGUILayout.TextField("Name: ", character.Name);
            GUILayout.Space(5f);
            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.Label("Global Config: ");
                character.Configuration = (PCharacterGlobalConfig)EditorGUILayout.ObjectField(character.Configuration, typeof(PCharacterGlobalConfig), false);
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(10f);
            GUILayout.Label("Character Configuration", GUIStyleUtils.GetStyle(GUIStyleType.NORMAL_HEADER));
            GUILayout.Space(10f);

            var smallHeader = GUIStyleUtils.GetStyle(GUIStyleType.NORMAL_HEADER);

            smallHeader.fontSize  = 12;
            smallHeader.fontStyle = FontStyle.Normal;
            GUILayout.Label("Character atlas", smallHeader);
            character.CharacterAtlas = (UnityEngine.U2D.SpriteAtlas)EditorGUILayout.ObjectField(character.CharacterAtlas, typeof(UnityEngine.U2D.SpriteAtlas), false);

            if (GUILayout.Button("Update Atlas"))
            {
                if (character.CharacterAtlas == null)
                {
                    Debug.LogError("Atlas is Null !");
                    return;
                }

                Sprite[] sprites = new Sprite[character.CharacterAtlas.spriteCount];
                character.CharacterAtlas.GetSprites(sprites);

                character.SpritesNames = new string[sprites.Length];

                for (int i = 0; i < sprites.Length; i++)
                {
                    var    curSprite    = sprites[i];
                    string formatedName = curSprite.name.Replace("(Clone)", string.Empty);
                    character.SpritesNames[i] = formatedName;
                }
            }

            GUILayout.Space(10f);

            var animationsArrayContent = characterSerialized.FindProperty("Animations");

            characterSerialized.Update();
            // bool showAnimations = EditorGUILayout.PropertyField(animationsArrayContent);

            // if (showAnimations)
            {
                EditorGUILayout.BeginHorizontal();
                {
                    int addAnimationButtonWidht = 50;
                    GUILayout.Space(Screen.width / 2 - addAnimationButtonWidht / 2);
                    if (GUILayout.Button("+", GUILayout.Width(addAnimationButtonWidht), GUILayout.Height(50)))
                    {
                        PCharacterAnimation newAnimation = new PCharacterAnimation();
                        newAnimation.PFrames = new PFrame[0];
                        ArrayUtility.Add(ref character.Animations, newAnimation);
                    }
                }
                // GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();

                EditorGUI.indentLevel++;
                for (int i = 0; i < character.Animations.Length; i++)
                {
                    var curAnimation = character.Animations[i];
                    DrawnAnimationContent(character, curAnimation);
                }
                EditorGUI.indentLevel--;
            }

            EditorUtility.SetDirty(target);
        }
示例#4
0
    void DrawCameraGUI(tk2dCamera target, bool complete)
    {
        bool allowProjectionParameters = target.SettingsRoot == target;
        bool oldGuiEnabled = GUI.enabled;

        SerializedObject so = this.serializedObject;
        SerializedObject cam = new SerializedObject( target.camera );

        SerializedProperty m_ClearFlags = cam.FindProperty("m_ClearFlags");
        SerializedProperty m_BackGroundColor = cam.FindProperty("m_BackGroundColor");
        SerializedProperty m_CullingMask = cam.FindProperty("m_CullingMask");
        SerializedProperty m_TargetTexture = cam.FindProperty("m_TargetTexture");
        SerializedProperty m_Near = cam.FindProperty("near clip plane");
        SerializedProperty m_Far = cam.FindProperty("far clip plane");
        SerializedProperty m_Depth = cam.FindProperty("m_Depth");
        SerializedProperty m_RenderingPath = cam.FindProperty("m_RenderingPath");
        SerializedProperty m_HDR = cam.FindProperty("m_HDR");

        if (complete) {
            EditorGUILayout.PropertyField( m_ClearFlags );
            EditorGUILayout.PropertyField( m_BackGroundColor );
            EditorGUILayout.PropertyField( m_CullingMask );
            EditorGUILayout.Space();
        }

        tk2dCameraSettings cameraSettings = target.CameraSettings;
        tk2dCameraSettings inheritedSettings = target.SettingsRoot.CameraSettings;
        TransparencySortMode transparencySortMode = inheritedSettings.transparencySortMode;

        GUI.enabled &= allowProjectionParameters;
        inheritedSettings.projection = (tk2dCameraSettings.ProjectionType)EditorGUILayout.EnumPopup("Projection", inheritedSettings.projection);
        EditorGUI.indentLevel++;
        if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Orthographic) {
            inheritedSettings.orthographicType = (tk2dCameraSettings.OrthographicType)EditorGUILayout.EnumPopup("Type", inheritedSettings.orthographicType);
            switch (inheritedSettings.orthographicType) {
                case tk2dCameraSettings.OrthographicType.OrthographicSize:
                    inheritedSettings.orthographicSize = Mathf.Max( 0.001f, EditorGUILayout.FloatField("Orthographic Size", inheritedSettings.orthographicSize) );
                    break;
                case tk2dCameraSettings.OrthographicType.PixelsPerMeter:
                    inheritedSettings.orthographicPixelsPerMeter = Mathf.Max( 0.001f, EditorGUILayout.FloatField("Pixels per Meter", inheritedSettings.orthographicPixelsPerMeter) );
                    break;
            }
            inheritedSettings.orthographicOrigin = (tk2dCameraSettings.OrthographicOrigin)EditorGUILayout.EnumPopup("Origin", inheritedSettings.orthographicOrigin);
        }
        else if (inheritedSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) {
            inheritedSettings.fieldOfView = EditorGUILayout.Slider("Field of View", inheritedSettings.fieldOfView, 1, 179);
            transparencySortMode = (TransparencySortMode)EditorGUILayout.EnumPopup("Sort mode", transparencySortMode);
        }
        EditorGUI.indentLevel--;
        GUI.enabled = oldGuiEnabled;

        if (complete) {
            EditorGUILayout.Space();
            GUILayout.Label("Clipping Planes");
            GUILayout.BeginHorizontal();
            GUILayout.Space(14);
            GUILayout.Label("Near");
            if (m_Near != null) EditorGUILayout.PropertyField(m_Near, GUIContent.none, GUILayout.Width(60) );
            GUILayout.Label("Far");
            if (m_Far != null) EditorGUILayout.PropertyField(m_Far, GUIContent.none, GUILayout.Width(60) );
            GUILayout.EndHorizontal();
            cameraSettings.rect = EditorGUILayout.RectField("Normalized View Port Rect", cameraSettings.rect);

            EditorGUILayout.Space();
            if (m_Depth != null) EditorGUILayout.PropertyField(m_Depth);
            if (m_RenderingPath != null) EditorGUILayout.PropertyField(m_RenderingPath);
            if (m_TargetTexture != null) EditorGUILayout.PropertyField(m_TargetTexture);
            if (m_HDR != null) EditorGUILayout.PropertyField(m_HDR);
        }

        cam.ApplyModifiedProperties();
        so.ApplyModifiedProperties();

        if (transparencySortMode != inheritedSettings.transparencySortMode) {
            inheritedSettings.transparencySortMode = transparencySortMode;
            target.camera.transparencySortMode = transparencySortMode; // Change immediately in the editor
            EditorUtility.SetDirty(target);
            EditorUtility.SetDirty(target.camera);
        }
    }
示例#5
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);

            position.height = 16;
            Rect lineRect = new Rect(position.x, position.y + 5, position.width, 16);

            if (property.FindPropertyRelative("gameEventData").objectReferenceValue != null)
            {
                Rect totalRect = position;
                totalRect.height = GetPropertyHeight(property, new GUIContent());
                totalRect.x     -= 2;
                totalRect.width += 4;

                GUI.Box(totalRect, "", EditorStyles.helpBox);
            }

            Rect valueRect = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

            if (property.FindPropertyRelative("gameEventData").objectReferenceValue != null)
            {
                valueRect.y += 5;
            }

            EditorGUI.PropertyField(valueRect, property.FindPropertyRelative("gameEventData"), GUIContent.none);

            if (property.FindPropertyRelative("gameEventData").objectReferenceValue != null)
            {
                valueRect.y += 18;
                lineRect.y  += 18;
                EditorGUI.PropertyField(valueRect, property.FindPropertyRelative("delay"));

                valueRect.y += 18;
                lineRect.y  += 18;
                EditorGUI.PropertyField(valueRect, property.FindPropertyRelative("delayType"));

                SerializedObject gameEventObject = new SerializedObject(property.FindPropertyRelative("gameEventData").objectReferenceValue);

                //Objects
                int numObjects = gameEventObject.FindProperty("eventObjects").arraySize;
                property.FindPropertyRelative("objects").arraySize = numObjects;

                if (numObjects > 0)
                {
                    lineRect.y += 18;
                    EditorGUI.LabelField(lineRect, "    Objects", EditorStyles.boldLabel);
                }

                for (int i = 0; i < numObjects; i++)
                {
                    lineRect.y += 18;

                    SerializedProperty objectNameProperty = gameEventObject.FindProperty(string.Format("eventObjects.Array.data[{0}].objectID", i));
                    SerializedProperty objectTypeProperty = gameEventObject.FindProperty(string.Format("eventObjects.Array.data[{0}].type", i));
                    valueRect = EditorGUI.PrefixLabel(lineRect, new GUIContent(string.Format("     • {0}", objectNameProperty.stringValue)));

                    property.FindPropertyRelative(string.Format("objects.Array.data[{0}].id", i)).stringValue = objectNameProperty.stringValue;
                    SerializedProperty objectValueProperty = property.FindPropertyRelative(string.Format("objects.Array.data[{0}].value", i));
                    objectValueProperty.objectReferenceValue = EditorGUI.ObjectField(valueRect, objectValueProperty.objectReferenceValue, GameEventData.TypeFromEnum((GameEventData.SupportedObjectType)objectTypeProperty.enumValueIndex), true);

                    if (objectValueProperty.objectReferenceValue != null)
                    {
                        if (objectValueProperty.objectReferenceValue is CustomValueData)
                        {
                            CustomValueData cvd = (CustomValueData)objectValueProperty.objectReferenceValue;
                            lineRect.y += 18;

                            if (cvd.type == CustomValueData.ValueType.Bool)
                            {
                                EditorGUI.LabelField(lineRect, " ", "     (Bool Type)", EditorStyles.boldLabel);
                            }
                            else if (cvd.type == CustomValueData.ValueType.Int)
                            {
                                EditorGUI.LabelField(lineRect, " ", "     (int Type)", EditorStyles.boldLabel);
                            }
                            else if (cvd.type == CustomValueData.ValueType.Float)
                            {
                                EditorGUI.LabelField(lineRect, " ", "     (Float Type)", EditorStyles.boldLabel);
                            }
                            else if (cvd.type == CustomValueData.ValueType.String)
                            {
                                EditorGUI.LabelField(lineRect, " ", "     (String Type)", EditorStyles.boldLabel);
                            }
                        }
                    }
                }

                //Bools
                int numBools = gameEventObject.FindProperty("eventBools").arraySize;
                property.FindPropertyRelative("bools").arraySize = numBools;

                if (numBools > 0)
                {
                    lineRect.y += 18;
                    EditorGUI.LabelField(lineRect, "    Bools", EditorStyles.boldLabel);
                }

                for (int i = 0; i < numBools; i++)
                {
                    lineRect.y += 18;

                    SerializedProperty boolNameProperty = gameEventObject.FindProperty(string.Format("eventBools.Array.data[{0}]", i));
                    valueRect = EditorGUI.PrefixLabel(lineRect, new GUIContent(string.Format("     • {0}", boolNameProperty.stringValue)));

                    property.FindPropertyRelative(string.Format("bools.Array.data[{0}].id", i)).stringValue = boolNameProperty.stringValue;
                    SerializedProperty boolValueProperty = property.FindPropertyRelative(string.Format("bools.Array.data[{0}].value", i));
                    EditorGUI.PropertyField(valueRect, boolValueProperty, new GUIContent());
                }

                //Ints
                int numInts = gameEventObject.FindProperty("eventInts").arraySize;
                property.FindPropertyRelative("ints").arraySize = numInts;

                if (numInts > 0)
                {
                    lineRect.y += 18;
                    EditorGUI.LabelField(lineRect, "    Ints", EditorStyles.boldLabel);
                }

                for (int i = 0; i < numInts; i++)
                {
                    lineRect.y += 18;

                    SerializedProperty intNameProperty = gameEventObject.FindProperty(string.Format("eventInts.Array.data[{0}]", i));
                    valueRect = EditorGUI.PrefixLabel(lineRect, new GUIContent(string.Format("     • {0}", intNameProperty.stringValue)));

                    property.FindPropertyRelative(string.Format("ints.Array.data[{0}].id", i)).stringValue = intNameProperty.stringValue;
                    SerializedProperty intValueProperty = property.FindPropertyRelative(string.Format("ints.Array.data[{0}].value", i));
                    EditorGUI.PropertyField(valueRect, intValueProperty, new GUIContent());
                }

                //Floats
                int numFloats = gameEventObject.FindProperty("eventFloats").arraySize;
                property.FindPropertyRelative("floats").arraySize = numFloats;

                if (numFloats > 0)
                {
                    lineRect.y += 18;
                    EditorGUI.LabelField(lineRect, "    Floats", EditorStyles.boldLabel);
                }

                for (int i = 0; i < numFloats; i++)
                {
                    lineRect.y += 18;

                    SerializedProperty floatNameProperty = gameEventObject.FindProperty(string.Format("eventFloats.Array.data[{0}]", i));
                    valueRect = EditorGUI.PrefixLabel(lineRect, new GUIContent(string.Format("     • {0}", floatNameProperty.stringValue)));

                    property.FindPropertyRelative(string.Format("floats.Array.data[{0}].id", i)).stringValue = floatNameProperty.stringValue;
                    SerializedProperty floatValueProperty = property.FindPropertyRelative(string.Format("floats.Array.data[{0}].value", i));
                    EditorGUI.PropertyField(valueRect, floatValueProperty, new GUIContent());
                }

                //Strings
                int numStrings = gameEventObject.FindProperty("eventStrings").arraySize;
                property.FindPropertyRelative("strings").arraySize = numStrings;

                if (numStrings > 0)
                {
                    lineRect.y += 18;
                    EditorGUI.LabelField(lineRect, "    Strings", EditorStyles.boldLabel);
                }

                for (int i = 0; i < numStrings; i++)
                {
                    lineRect.y += 18;

                    SerializedProperty stringNameProperty = gameEventObject.FindProperty(string.Format("eventStrings.Array.data[{0}]", i));
                    valueRect = EditorGUI.PrefixLabel(lineRect, new GUIContent(string.Format("     • {0}", stringNameProperty.stringValue)));

                    property.FindPropertyRelative(string.Format("strings.Array.data[{0}].id", i)).stringValue = stringNameProperty.stringValue;
                    SerializedProperty stringValueProperty = property.FindPropertyRelative(string.Format("strings.Array.data[{0}].value", i));
                    EditorGUI.PropertyField(valueRect, stringValueProperty, new GUIContent());
                }
            }

            property.serializedObject.ApplyModifiedProperties();

            EditorGUI.EndProperty();
        }
示例#6
0
    public override void OnInspectorGUI()
    {
        m_object.Update();
        DrawDefaultInspector();

        OutlineFX _2dxScript = (OutlineFX)target;

        Texture2D icon = Resources.Load("2dxfxinspector") as Texture2D;

        if (icon)
        {
            Rect  r;
            float ih     = icon.height;
            float iw     = icon.width;
            float result = ih / iw;
            float w      = Screen.width;
            result = result * w;
            r      = GUILayoutUtility.GetRect(ih, result);
            EditorGUI.DrawTextureTransparent(r, icon);
        }

        EditorGUILayout.PropertyField(m_object.FindProperty("ActiveUpdate"), new GUIContent("Active Update", "Active Update, for animation / Animator only")); EditorGUILayout.PropertyField(m_object.FindProperty("ForceMaterial"), new GUIContent("Shared Material", "Use a unique material, reduce drastically the use of draw call"));

        if (_2dxScript.ForceMaterial == null)
        {
            _2dxScript.ActiveChange = true;
        }
        else
        {
            if (GUILayout.Button("Remove Shared Material"))
            {
                _2dxScript.ForceMaterial = null;
                _2dxScript.ShaderChange  = 1;
                _2dxScript.ActiveChange  = true;
                _2dxScript.CallUpdate();
            }

            EditorGUILayout.PropertyField(m_object.FindProperty("ActiveChange"), new GUIContent("Change Material Property", "Change The Material Property"));
        }

        if (_2dxScript.ActiveChange)
        {
            EditorGUILayout.BeginVertical("Box");

            Texture2D icone = Resources.Load("2dxfx-icon-value") as Texture2D;
            EditorGUILayout.PropertyField(m_object.FindProperty("_ColorX"), new GUIContent("Outline color", icone, "Change the color of the outline"));

            icone = Resources.Load("2dxfx-icon-value") as Texture2D;
            EditorGUILayout.PropertyField(m_object.FindProperty("_OutLineSpread"), new GUIContent("Outline size", icone, "Change the size of the outline"));

            EditorGUILayout.BeginVertical("Box");

            icone = Resources.Load("2dxfx-icon-fade") as Texture2D;
            EditorGUILayout.PropertyField(m_object.FindProperty("_Alpha"), new GUIContent("Fading", icone, "Fade from nothing to showing"));

            EditorGUILayout.EndVertical();
            EditorGUILayout.EndVertical();
        }

        m_object.ApplyModifiedProperties();
    }
示例#7
0
 void OnEnable()
 {
     e_object          = new SerializedObject(target);
     e_subsurfaceColor = e_object.FindProperty("subsurfaceColor");
     e_maskSource      = e_object.FindProperty("maskSource");
 }
    public override void OnInspectorGUI()
    {
        var groups = Manager.Base.Sounds.Where(s => s.Type.Contains('/')).GroupBy(e => e.Type.Split('/').First()).Select(e => e.Key);

        serializedObject.Update();

        var audioBase   = serializedObject.FindProperty("Base");
        var audioBaseSO = new SerializedObject(audioBase.objectReferenceValue);

        audioBaseSO.Update();
        var sounds = audioBaseSO.FindProperty("Sounds");

        EditorGUILayout.PropertyField(audioBase);


        EditorGUILayout.Space();
        if (GUILayout.Toggle(_unfoldedGroup == string.Empty, "All", EditorStyles.toolbarButton))
        {
            _unfoldedGroup = string.Empty;
        }

        foreach (var g in groups)
        {
            if (GUILayout.Toggle(_unfoldedGroup == g, g, EditorStyles.toolbarButton) && _unfoldedGroup != g)
            {
                _unfoldedGroup = g;
                _unfoldedSound = string.Empty;
            }
        }
        EditorGUILayout.Space();

        int toReplace   = -1;
        var soundsArray = AudioManagerUtils.AsArray(sounds);

        for (int index = 0; index < soundsArray.Length; index++)
        {
            var sound = soundsArray[index];

            var soundType  = sound.FindPropertyRelative("Type");
            var clips      = sound.FindPropertyRelative("Clips");
            var clipsArray = AudioManagerUtils.AsArray(clips);

            bool toDraw = !soundType.stringValue.Contains('/') || soundType.stringValue.StartsWith(_unfoldedGroup);
            if (!toDraw)
            {
                continue;
            }

            bool unfolded = soundType.stringValue == _unfoldedSound;


            AudioManagerUtils.DrawLine(AudioManagerUtils.Blue);

            if (clipsArray.Length == 0 || clipsArray.Any(c => c.objectReferenceValue == null))
            {
                AudioManagerUtils.DrawBackgroundBox(AudioManagerUtils.Red, 28, -4);
            }
            if (clipsArray.Length > 1)
            {
                AudioManagerUtils.DrawBackgroundBox(AudioManagerUtils.Yellow, 28, -4);
            }

            using (new GUILayout.HorizontalScope())
            {
                if (GUILayout.Button(unfolded ? AudioManagerUtils.ArrowUp : AudioManagerUtils.ArrowDown, EditorStyles.toolbarButton, GUILayout.Width(20)))
                {
                    _unfoldedSound = unfolded ? string.Empty : soundType.stringValue;
                }

                var newType = EditorGUILayout.DelayedTextField(soundType.stringValue);
                if (soundType.stringValue != newType)
                {
                    soundType.stringValue = newType;
                    if (newType.Contains('/'))
                    {
                        _unfoldedGroup = newType.Split('/')[0];
                    }
                }

                // Replace clips of Sound with new ones
                var newClipsToReplace = AudioManagerUtils.DropArea <AudioClip>("replace", 20);
                if (newClipsToReplace != null)
                {
                    AudioManagerUtils.ReplaceArray(clips, newClipsToReplace.ToArray <Object>());
                }

                if (unfolded)
                {
                    if (GUILayout.Button("x", EditorStyles.toolbarButton, GUILayout.Width(20)))
                    {
                        toReplace = index;
                    }
                }
            }


            // Draw Clips of Sound if unfolded
            if (_unfoldedSound != soundType.stringValue)
            {
                continue;
            }

            EditorGUI.indentLevel++;
            for (int y = 0; y < clipsArray.Length; y++)
            {
                clipsArray[y].objectReferenceValue = (AudioClip)EditorGUILayout.ObjectField(clipsArray[y].objectReferenceValue, typeof(AudioClip), false);
            }
            EditorGUI.indentLevel--;
        }

        EditorGUILayout.Space();
        var newClips = AudioManagerUtils.DropArea <AudioClip>("Drop to add sound", 50);

        if (newClips != null)
        {
            var newSound      = AudioManagerUtils.NewElement(sounds);
            var newSoundType  = newSound.FindPropertyRelative("Type");
            var newSoundId    = newSound.FindPropertyRelative("Id");
            var newSoundClips = newSound.FindPropertyRelative("Clips");

            newSoundType.stringValue = string.IsNullOrEmpty(_unfoldedGroup) ? "Custom" : _unfoldedGroup;
            newSoundId.stringValue   = Guid.NewGuid().ToString();
            AudioManagerUtils.ReplaceArray(newSoundClips, newClips.ToArray <Object>());
        }
        EditorGUILayout.Space();

        if (toReplace >= 0)
        {
            sounds.DeleteArrayElementAtIndex(toReplace);
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(Manager);
            serializedObject.ApplyModifiedProperties();
            audioBaseSO.ApplyModifiedProperties();
        }
    }
    void OnEnable()
    {
        sObj = new SerializedObject(target);

        lightType      = sObj.FindProperty("lightType");
        lightDetail    = sObj.FindProperty("lightDetail");
        lightColor     = sObj.FindProperty("lightColor");
        sweepSize      = sObj.FindProperty("coneAngle");
        sweepStart     = sObj.FindProperty("coneStart");
        lightRadius    = sObj.FindProperty("lightRadius");
        lightMaterial  = sObj.FindProperty("lightMaterial");
        useEvents      = sObj.FindProperty("useEvents");
        shadowLayer    = sObj.FindProperty("shadowLayer");
        beamSize       = sObj.FindProperty("beamSize");
        beamRange      = sObj.FindProperty("beamRange");
        pivotPoint     = sObj.FindProperty("pivotPoint");
        pivotPointType = sObj.FindProperty("pivotPointType");
        uvTiling       = sObj.FindProperty("uvTiling");
        uvOffset       = sObj.FindProperty("uvOffset");

        #if !(UNITY_2_6 || UNITY_2_6_1 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
        Undo.undoRedoPerformed += UndoCall;
        #endif
    }
        void OnEnable () {
            serObj = new SerializedObject (target);

            screenBlendMode = serObj.FindProperty("screenBlendMode");
            hdr = serObj.FindProperty("hdr");

            sepBlurSpread = serObj.FindProperty("sepBlurSpread");
            useSrcAlphaAsMask = serObj.FindProperty("useSrcAlphaAsMask");

            bloomIntensity = serObj.FindProperty("bloomIntensity");
            bloomthreshold = serObj.FindProperty("bloomThreshold");
            bloomBlurIterations = serObj.FindProperty("bloomBlurIterations");

            lensflares = serObj.FindProperty("lensflares");

            lensflareMode = serObj.FindProperty("lensflareMode");
            hollywoodFlareBlurIterations = serObj.FindProperty("hollywoodFlareBlurIterations");
            hollyStretchWidth = serObj.FindProperty("hollyStretchWidth");
            lensflareIntensity = serObj.FindProperty("lensflareIntensity");
            lensflarethreshold = serObj.FindProperty("lensflareThreshold");
            flareColorA = serObj.FindProperty("flareColorA");
            flareColorB = serObj.FindProperty("flareColorB");
            flareColorC = serObj.FindProperty("flareColorC");
            flareColorD = serObj.FindProperty("flareColorD");
            lensFlareVignetteMask = serObj.FindProperty("lensFlareVignetteMask");

            tweakMode = serObj.FindProperty("tweakMode");
        }
示例#11
0
 public static void InitializeProperties(SerializedObject serializedObject)
 {
     TexturesProperty           = serializedObject.FindProperty("textures");
     SpritesProperty            = serializedObject.FindProperty("sprites");
     DefaultPivotProperty       = serializedObject.FindProperty("defaultPivot");
     KeepOriginalPivotProperty  = serializedObject.FindProperty("keepOriginalPivot");
     DecoupleSpriteDataProperty = serializedObject.FindProperty("decoupleSpriteData");
     AtlasSizeLimitProperty     = serializedObject.FindProperty("atlasSizeLimit");
     ForceSquareProperty        = serializedObject.FindProperty("forceSquare");
     PPUProperty                        = serializedObject.FindProperty("pixelsPerUnit");
     UnitSizeProperty                   = serializedObject.FindProperty("diceUnitSize");
     PaddingProperty                    = serializedObject.FindProperty("padding");
     UVInsetProperty                    = serializedObject.FindProperty("uvInset");
     InputFolderProperty                = serializedObject.FindProperty("inputFolder");
     IncludeSubfoldersProperty          = serializedObject.FindProperty("includeSubfolders");
     PrependSubfolderNamesProperty      = serializedObject.FindProperty("prependSubfolderNames");
     GeneratedSpritesFolderGuidProperty = serializedObject.FindProperty("generatedSpritesFolderGuid");
     LastRatioValueProperty             = serializedObject.FindProperty("lastRatioValue");
 }
 protected override void PropertyField()
 {
     EditorGUILayout.PropertyField(serializedCountdownAnimation.FindProperty("skipCountdown"), new GUIContent("skipCountdown"));
 }
示例#13
0
//	private Guid   cacheGuid               = Guid.Empty;
//	// When indexes update, there are three likely scenarios:
//	//     1) ID has not changed.
//	//     2) ID has shifted by a few values due to sorting.
//	//     3) Content has been removed, and therefore there is no ID.
//	private int ReassociateContentID(int index, TrackableType markerType, string content) {
//		if (string.CompareOrdinal(ARToolKitAssetManager.AllMarkers[index], content) == 0) {
//			return index;
//		} else {
//			for (int i = 0; i < ARToolKitAssetManager.
//		}
//	}

    public override void OnInspectorGUI()
    {
        // Get the ARMarker that this panel will edit.
        ARTrackable arMarker = (ARTrackable)target;

        if (null == arMarker)
        {
            return;
        }
        // Attempt to load. Might not work out if e.g. for a single marker, pattern hasn't been
        // assigned yet, or for an NFT marker, dataset hasn't been specified.
        if (arMarker.UID == ARTrackable.NO_ID)
        {
            PluginFunctions.arwInitialiseAR();
            Debug.Log("ARTrackableEditor:Editor::OnInspectorGUI(): calling Load()");
            arMarker.Load();
            Debug.Log("ARTrackableEditor:Editor::OnInspectorGUI(): arMarker.UID == " + arMarker.UID);
        }

        //Check if a new image was dropped into the Project directory
        string        path = Application.streamingAssetsPath + "/" + ARToolKitAssetManager.IMAGES_DIRECTORY_NAME;
        DirectoryInfo dir  = new DirectoryInfo(path);

        FileInfo[] imageFileList = dir.GetFiles("*.jpg").Union(dir.GetFiles("*.jpeg")).ToArray();
        if (imageFileList != null && ARToolKitAssetManager.Images != null && imageFileList.Length != ARToolKitAssetManager.Images.Length)
        {
            if (imageFileList.Length < ARToolKitAssetManager.Images.Length)
            {
                //An image was deleted from the file system so we might have an empty ARTrackable now
                Debug.unityLogger.Log(LogType.Warning, "<color=red>Trackable image removed. Please check all ARTrackables and make sure that they have an image assigned.</color>");
            }
            //We found a new trackable in the file system or a trackable was removed lets reload the trackables.
            ARToolKitAssetManager.Reload();
        }

        //Draw the drag n drop area
        DropAreaGUI();

        int selectedMarker = ArrayUtility.IndexOf(ARToolKitAssetManager.AllMarkers, arMarker.EditorMarkerName);

        arMarker.EditorMarkerIndex = EditorGUILayout.Popup("Marker", selectedMarker, ARToolKitAssetManager.AllMarkers);

        bool newSelection = false;

        if (arMarker.EditorMarkerIndex < 0)
        {
            //An image was deleted from the file system so we have an empty ARTrackable now
            Debug.unityLogger.Log(LogType.Warning, "<color=red>Trackable image removed. Please check the ARTrackable and make sure that is has an image assigned.</color>");
            return;
        }
        else
        {
            if (string.CompareOrdinal(arMarker.EditorMarkerName, ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex]) != 0)
            {
                newSelection = true;
                arMarker.EditorMarkerName = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex];
            }
        }

        ARTrackable.TrackableType markerType = DetermineTrackableType(arMarker.EditorMarkerIndex);
        if (arMarker.Type != markerType)
        {
            arMarker.ClearUnusedValues();
            arMarker.Type = markerType;
            UpdatePatternDetectionMode();
        }

        EditorGUILayout.LabelField("Type ", ARTrackable.TrackableTypeNames[arMarker.Type]);

        EditorGUILayout.LabelField("Unique ID", (arMarker.UID == ARTrackable.NO_ID ? "Not Loaded": arMarker.UID.ToString()));

        EditorGUILayout.BeginHorizontal();
        // Draw all the marker images
        if (arMarker.Patterns != null)
        {
            for (int i = 0; i < arMarker.Patterns.Length; ++i)
            {
                EditorGUILayout.Separator();
                GUILayout.Label(new GUIContent(string.Format("Pattern {0}, {1}m", i, arMarker.Patterns[i].width.ToString("n3")), arMarker.Patterns[i].texture), GUILayout.ExpandWidth(false));                 // n3 -> 3 decimal places.
            }
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Separator();

        switch (arMarker.Type)
        {
        case ARTrackable.TrackableType.TwoD:
            if (newSelection)
            {
                arMarker.TwoDImageName = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex];
            }
            float twoDImageHeight = EditorGUILayout.FloatField("Image height", arMarker.TwoDImageHeight);
            if (twoDImageHeight != arMarker.TwoDImageHeight)
            {
                EditorUtility.SetDirty(arMarker);
                arMarker.TwoDImageHeight = twoDImageHeight;
            }

            float   width = 0.0f, height = 0.0f;
            int     imageWidth = 0, imageHeight = 0;
            float[] transformation = new float[16];

            Debug.Log("ARTrackableEditor:Editor::OnInspectorGUI(): calling PluginFunctions.arwGetTrackableAppearanceConfig(arMarker.UID == " + arMarker.UID + ")");
            if (PluginFunctions.arwGetTrackableAppearanceConfig(arMarker.UID, 0, transformation, out width, out height, out imageWidth, out imageHeight))
            {
                Color32[] imagePixels = new Color32[imageWidth * imageHeight];
                if (PluginFunctions.arwGetTrackableAppearanceImage(arMarker.UID, 0, imagePixels))
                {
                    //Set the texture with the trackable appearance.
                    Texture2D texture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGBA32, true);
                    texture.SetPixels32(imagePixels);
                    texture.Apply();

                    //Display label and texture to the user
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("Trackable Appearance");

                    //Resize texture for viewport with max with and height
                    GUILayout.Label(ARTrackableAppearanceScale.BilinearWithMaxSize(texture, 200, 200));
                    EditorGUILayout.EndHorizontal();
                }
            }
            break;

        case ARTrackable.TrackableType.Square:
            if (newSelection)
            {
                arMarker.PatternContents = GetPatternContents(ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex]);
            }
            arMarker.PatternWidth          = EditorGUILayout.FloatField("Pattern Width (m)", arMarker.PatternWidth);
            arMarker.UseContPoseEstimation = EditorGUILayout.Toggle("Contstant Pose Estimation", arMarker.UseContPoseEstimation);
            break;

        case ARTrackable.TrackableType.SquareBarcode:
            if (newSelection)
            {
                string[] idArray = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex].Split(' ');
                arMarker.BarcodeID = int.Parse(idArray[idArray.Length - 1]);
            }
            arMarker.PatternWidth          = EditorGUILayout.FloatField("Pattern Width (m)", arMarker.PatternWidth);
            arMarker.UseContPoseEstimation = EditorGUILayout.Toggle("Contstant Pose Estimation", arMarker.UseContPoseEstimation);
            break;

        case ARTrackable.TrackableType.Multimarker:
            if (newSelection)
            {
                arMarker.MultiConfigFile = ARToolKitAssetManager.AllMarkers[arMarker.EditorMarkerIndex];
            }
            break;
        }

        EditorGUILayout.Separator();

        arMarker.Filtered = EditorGUILayout.Toggle("Filter Pose", arMarker.Filtered);
        if (arMarker.Filtered)
        {
            arMarker.FilterSampleRate = EditorGUILayout.Slider("Sample Rate", arMarker.FilterSampleRate, 1.0f, 30.0f);
            arMarker.FilterCutoffFreq = EditorGUILayout.Slider("Cutoff Frequency", arMarker.FilterCutoffFreq, 1.0f, 30.0f);
        }

        if (arMarker.Type == ARTrackable.TrackableType.Square || arMarker.Type == ARTrackable.TrackableType.SquareBarcode || arMarker.Type == ARTrackable.TrackableType.Multimarker)
        {
            showGlobalSquareOptions = EditorGUILayout.Foldout(showGlobalSquareOptions, "Global Square Tracking Options");
            if (showGlobalSquareOptions)
            {
                ARController.Instance.TemplateSize = EditorGUILayout.IntSlider("Template Size (bits)", ARController.Instance.TemplateSize, 16, 64);

                int currentTemplateCountMax = ARController.Instance.TemplateCountMax;
                int newTemplateCountMax     = EditorGUILayout.IntField("Maximum Template Count", currentTemplateCountMax);
                if (newTemplateCountMax != currentTemplateCountMax && newTemplateCountMax > 0)
                {
                    ARController.Instance.TemplateCountMax = newTemplateCountMax;
                }

                bool trackInColor = EditorGUILayout.Toggle("Track Templates in Color", ARController.Instance.trackTemplatesInColor);
                if (trackInColor != ARController.Instance.trackTemplatesInColor)
                {
                    ARController.Instance.trackTemplatesInColor = trackInColor;
                    UpdatePatternDetectionMode();
                }

                ARController.Instance.BorderSize    = UnityEngine.Mathf.Clamp(EditorGUILayout.FloatField("Border Size (%)", ARController.Instance.BorderSize), 0.0f, 0.5f);
                ARController.Instance.LabelingMode  = (ARController.ARToolKitLabelingMode)EditorGUILayout.EnumPopup("Marker Border Color", ARController.Instance.LabelingMode);
                ARController.Instance.ImageProcMode = (ARController.ARToolKitImageProcMode)EditorGUILayout.EnumPopup("Image Processing Mode", ARController.Instance.ImageProcMode);
            }
        }

        var obj  = new SerializedObject(arMarker);
        var prop = obj.FindProperty("eventReceivers");

        EditorGUILayout.PropertyField(prop, new GUIContent("Event Receivers"), true);
        obj.ApplyModifiedProperties();
    }
示例#14
0
        public static void UpdateRenderer(SpriteMeshInstance spriteMeshInstance, bool undo = true)
        {
            if (!spriteMeshInstance)
            {
                return;
            }

            SerializedObject spriteMeshInstaceSO = new SerializedObject(spriteMeshInstance);

            SpriteMesh spriteMesh = spriteMeshInstaceSO.FindProperty("m_SpriteMesh").objectReferenceValue as SpriteMesh;

            if (spriteMesh)
            {
                Material[] materials  = spriteMesh.sharedMaterials;
                Mesh       sharedMesh = spriteMesh.sharedMesh;

                if (sharedMesh.bindposes.Length > 0 && spriteMeshInstance.bones.Count > sharedMesh.bindposes.Length)
                {
                    spriteMeshInstance.bones = spriteMeshInstance.bones.GetRange(0, sharedMesh.bindposes.Length);
                }

                if (CanEnableSkinning(spriteMeshInstance))
                {
                    MeshFilter   meshFilter   = spriteMeshInstance.cachedMeshFilter;
                    MeshRenderer meshRenderer = spriteMeshInstance.cachedRenderer as MeshRenderer;

                    if (meshFilter)
                    {
                        if (undo)
                        {
                            Undo.DestroyObjectImmediate(meshFilter);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(meshFilter);
                        }
                    }
                    if (meshRenderer)
                    {
                        if (undo)
                        {
                            Undo.DestroyObjectImmediate(meshRenderer);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(meshRenderer);
                        }
                    }

                    SkinnedMeshRenderer skinnedMeshRenderer = spriteMeshInstance.cachedSkinnedRenderer;

                    if (!skinnedMeshRenderer)
                    {
                        if (undo)
                        {
                            skinnedMeshRenderer = Undo.AddComponent <SkinnedMeshRenderer>(spriteMeshInstance.gameObject);
                        }
                        else
                        {
                            skinnedMeshRenderer = spriteMeshInstance.gameObject.AddComponent <SkinnedMeshRenderer>();
                        }
                    }

                    skinnedMeshRenderer.bones = spriteMeshInstance.bones.ConvertAll(bone => bone.transform).ToArray();

                    if (spriteMeshInstance.bones.Count > 0)
                    {
                        skinnedMeshRenderer.rootBone = spriteMeshInstance.bones[0].transform;
                    }

                    skinnedMeshRenderer.sharedMaterials = materials;

                    EditorUtility.SetDirty(skinnedMeshRenderer);
                }
                else
                {
                    SkinnedMeshRenderer skinnedMeshRenderer = spriteMeshInstance.cachedSkinnedRenderer;
                    MeshFilter          meshFilter          = spriteMeshInstance.cachedMeshFilter;
                    MeshRenderer        meshRenderer        = spriteMeshInstance.cachedRenderer as MeshRenderer;

                    if (skinnedMeshRenderer)
                    {
                        if (undo)
                        {
                            Undo.DestroyObjectImmediate(skinnedMeshRenderer);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(skinnedMeshRenderer);
                        }
                    }

                    if (!meshFilter)
                    {
                        if (undo)
                        {
                            meshFilter = Undo.AddComponent <MeshFilter>(spriteMeshInstance.gameObject);
                        }
                        else
                        {
                            meshFilter = spriteMeshInstance.gameObject.AddComponent <MeshFilter>();
                        }

                        EditorUtility.SetDirty(meshFilter);
                    }

                    if (!meshRenderer)
                    {
                        if (undo)
                        {
                            meshRenderer = Undo.AddComponent <MeshRenderer>(spriteMeshInstance.gameObject);
                        }
                        else
                        {
                            meshRenderer = spriteMeshInstance.gameObject.AddComponent <MeshRenderer>();
                        }
                        meshRenderer.sharedMaterials = materials;

                        EditorUtility.SetDirty(meshRenderer);
                    }
                }
            }
        }
示例#15
0
        public static void UpdateAssets(SpriteMesh spriteMesh, SpriteMeshData spriteMeshData)
        {
            if (spriteMesh && spriteMeshData)
            {
                string spriteMeshPath = AssetDatabase.GetAssetPath(spriteMesh);

                SerializedObject   spriteMeshSO        = new SerializedObject(spriteMesh);
                SerializedProperty sharedMeshProp      = spriteMeshSO.FindProperty("m_SharedMesh");
                SerializedProperty sharedMaterialsProp = spriteMeshSO.FindProperty("m_SharedMaterials");

                if (!spriteMesh.sharedMesh)
                {
                    Mesh mesh = new Mesh();
                    mesh.hideFlags = HideFlags.HideInHierarchy;
                    AssetDatabase.AddObjectToAsset(mesh, spriteMeshPath);

                    spriteMeshSO.Update();
                    sharedMeshProp.objectReferenceValue = mesh;
                    spriteMeshSO.ApplyModifiedProperties();
                    EditorUtility.SetDirty(mesh);
                }

                spriteMesh.sharedMesh.name = spriteMesh.name;

                if (spriteMesh.sharedMaterials.Length == 0)
                {
                    Material material = new Material(Shader.Find("Sprites/Default"));
                    material.mainTexture = SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false);

                    AssetDatabase.AddObjectToAsset(material, spriteMeshPath);

                    spriteMeshSO.Update();
                    sharedMaterialsProp.arraySize = 1;
                    sharedMaterialsProp.GetArrayElementAtIndex(0).objectReferenceValue = material;
                    spriteMeshSO.ApplyModifiedProperties();
                }

                for (int i = 0; i < spriteMesh.sharedMaterials.Length; i++)
                {
                    Material material = spriteMesh.sharedMaterials [i];

                    if (material)
                    {
                        if (spriteMesh.sprite)
                        {
                            material.mainTexture = SpriteUtility.GetSpriteTexture(spriteMesh.sprite, false);
                        }

                        material.name      = spriteMesh.name + "_" + i;
                        material.hideFlags = HideFlags.HideInHierarchy;
                        EditorUtility.SetDirty(material);
                    }
                }

                spriteMeshData.hideFlags = HideFlags.HideInHierarchy;
                EditorUtility.SetDirty(spriteMeshData);

                int width  = 0;
                int height = 0;

                GetSpriteTextureSize(spriteMesh.sprite, ref width, ref height);

                Vector3[] vertices = GetMeshVertices(spriteMesh.sprite, spriteMeshData);

                Vector2 textureWidthHeightInv = new Vector2(1f / width, 1f / height);

                Vector2[] uvs = (new List <Vector2>(spriteMeshData.vertices)).ConvertAll(v => Vector2.Scale(v, textureWidthHeightInv)).ToArray();

                Vector3[] normals = (new List <Vector3>(vertices)).ConvertAll(v => Vector3.back).ToArray();

                BoneWeight[] boneWeightsData = spriteMeshData.boneWeights;

                if (boneWeightsData.Length != spriteMeshData.vertices.Length)
                {
                    boneWeightsData = new BoneWeight[spriteMeshData.vertices.Length];
                }

                List <UnityEngine.BoneWeight> boneWeights = new List <UnityEngine.BoneWeight>(boneWeightsData.Length);

                List <float> verticesOrder = new List <float>(spriteMeshData.vertices.Length);

                for (int i = 0; i < boneWeightsData.Length; i++)
                {
                    BoneWeight boneWeight = boneWeightsData[i];

                    List <KeyValuePair <int, float> > pairs = new List <KeyValuePair <int, float> >();
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex0, boneWeight.weight0));
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex1, boneWeight.weight1));
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex2, boneWeight.weight2));
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex3, boneWeight.weight3));

                    pairs = pairs.OrderByDescending(s => s.Value).ToList();

                    UnityEngine.BoneWeight boneWeight2 = new UnityEngine.BoneWeight();
                    boneWeight2.boneIndex0 = Mathf.Max(0, pairs[0].Key);
                    boneWeight2.boneIndex1 = Mathf.Max(0, pairs[1].Key);
                    boneWeight2.boneIndex2 = Mathf.Max(0, pairs[2].Key);
                    boneWeight2.boneIndex3 = Mathf.Max(0, pairs[3].Key);
                    boneWeight2.weight0    = pairs[0].Value;
                    boneWeight2.weight1    = pairs[1].Value;
                    boneWeight2.weight2    = pairs[2].Value;
                    boneWeight2.weight3    = pairs[3].Value;

                    boneWeights.Add(boneWeight2);

                    float vertexOrder = i;

                    if (spriteMeshData.bindPoses.Length > 0)
                    {
                        vertexOrder = spriteMeshData.bindPoses[boneWeight2.boneIndex0].zOrder * boneWeight2.weight0 +
                                      spriteMeshData.bindPoses[boneWeight2.boneIndex1].zOrder * boneWeight2.weight1 +
                                      spriteMeshData.bindPoses[boneWeight2.boneIndex2].zOrder * boneWeight2.weight2 +
                                      spriteMeshData.bindPoses[boneWeight2.boneIndex3].zOrder * boneWeight2.weight3;
                    }

                    verticesOrder.Add(vertexOrder);
                }

                List <WeightedTriangle> weightedTriangles = new List <WeightedTriangle>(spriteMeshData.indices.Length / 3);

                for (int i = 0; i < spriteMeshData.indices.Length; i += 3)
                {
                    int p1 = spriteMeshData.indices[i];
                    int p2 = spriteMeshData.indices[i + 1];
                    int p3 = spriteMeshData.indices[i + 2];

                    weightedTriangles.Add(new WeightedTriangle(p1, p2, p3,
                                                               verticesOrder[p1],
                                                               verticesOrder[p2],
                                                               verticesOrder[p3]));
                }

                weightedTriangles = weightedTriangles.OrderBy(t => t.weight).ToList();

                List <int> indices = new List <int>(spriteMeshData.indices.Length);

                for (int i = 0; i < weightedTriangles.Count; ++i)
                {
                    WeightedTriangle t = weightedTriangles[i];
                    indices.Add(t.p1);
                    indices.Add(t.p2);
                    indices.Add(t.p3);
                }

                List <Matrix4x4> bindposes = (new List <BindInfo>(spriteMeshData.bindPoses)).ConvertAll(p => p.bindPose);

                for (int i = 0; i < bindposes.Count; i++)
                {
                    Matrix4x4 bindpose = bindposes [i];

                    bindpose.m23 = 0f;

                    bindposes[i] = bindpose;
                }

                spriteMesh.sharedMesh.Clear();
                spriteMesh.sharedMesh.vertices    = vertices;
                spriteMesh.sharedMesh.uv          = uvs;
                spriteMesh.sharedMesh.triangles   = indices.ToArray();
                spriteMesh.sharedMesh.normals     = normals;
                spriteMesh.sharedMesh.boneWeights = boneWeights.ToArray();
                spriteMesh.sharedMesh.bindposes   = bindposes.ToArray();
                spriteMesh.sharedMesh.RecalculateBounds();

                RebuildBlendShapes(spriteMesh);
            }
        }
示例#16
0
 private void OnEnable()
 {
     data         = new SerializedObject(target);
     m_Effect     = data.FindProperty("m_Effect");
     LifeTime     = data.FindProperty("LifeTime");
     IsCarryer    = data.FindProperty("IsCarryer");
     BornBullet   = data.FindProperty("BornBullet");
     TeamEffect   = data.FindProperty("TeamEffect");
     IgnorGravity = data.FindProperty("IgnorGravity");
     HitForce     = data.FindProperty("HitForce");
     AttachTarget = data.FindProperty("AttachTarget");
     EffectTime   = data.FindProperty("EffectTime");
     Effectcolor  = data.FindProperty("Effectcolor");
     CrossOver    = data.FindProperty("CrossOver");
 }
        private void DrawListElement(Rect elementRect, SerializedProperty element, bool isSelected)
        {
            if (element.objectReferenceValue != null)
            {
                Rect rect = elementRect;
                rect.y     += 2;
                rect.height = m_LineHeight;

                SerializedObject   elementObj = new SerializedObject(element.objectReferenceValue);
                SerializedProperty stateName  = elementObj.FindProperty("m_stateName");
                SerializedProperty isActive   = elementObj.FindProperty("m_isActive");
                SerializedProperty actionID   = elementObj.FindProperty("m_actionID");


                CharacterAction action = (CharacterAction)element.objectReferenceValue;
                //  Action name.
                rect.width = elementRect.width * 0.40f;
                if (action.IsActive)
                {
                    EditorGUI.LabelField(rect, string.Format("{0} ({1})", action.GetType().Name, "Active"), m_ActiveActionTextStyle);
                }
                else
                {
                    EditorGUI.LabelField(rect, action.GetType().Name, m_DefaultActionTextStyle);
                }


                //  Action state name.
                rect.x               += elementRect.width * 0.40f;
                rect.width            = elementRect.width * 0.36f;
                stateName.stringValue = EditorGUI.TextField(rect, stateName.stringValue);
                //  Action ID
                //rect.x = elementRect.width * 0.85f;
                rect.x            = elementRect.width - 36;
                rect.width        = 36;
                actionID.intValue = EditorGUI.IntField(rect, actionID.intValue);

                //  Toggle Enable
                rect.x         = elementRect.width + 12;
                rect.width     = 36;
                action.enabled = EditorGUI.Toggle(rect, action.enabled);
                //isActive.boolValue = EditorGUI.Toggle(rect, isActive.boolValue);
                //isActive.boolValue = action.enabled;

                elementObj.ApplyModifiedProperties();



                Event evt = Event.current;
                if (elementRect.Contains(evt.mousePosition))
                {
                    if (evt.button == 1 && evt.isMouse && evt.type == EventType.MouseUp)
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(new GUIContent("Add"), false, () => TestContextMenu(action.GetType().Name));
                        menu.AddItem(new GUIContent("Remove"), false, () => TestContextMenu(action.GetType().Name));
                        menu.ShowAsContext();
                        //ChangeStateName(stateName, action.GetType().Name);
                    }
                }
                //else {
                //    if (evt.button == 0 && evt.isMouse && evt.type == EventType.MouseUp)
                //    {
                //        if(action != null) action = null;
                //    }
                //}
            }
        }
示例#18
0
    void OnAssetsGUI()
    {
        float vPos       = -scrollPosition.y;
        var   appendices = serializedObject.FindProperty("m_Appendices");

        if (appendices != null)
        {
            if (assets == null)
            {
                assets      = new List <AssetEntry>();
                outputFiles = new Dictionary <string, int>();
                assetTypes  = new Dictionary <string, int>();
                for (int i = 0; i < appendices.arraySize; i++)
                {
                    var appendix = appendices.GetArrayElementAtIndex(i);
                    if (appendix.objectReferenceValue.GetType() == typeof(Object))
                    {
                        var appendixSO = new SerializedObject(appendix.objectReferenceValue);
                        if (appendixSO.FindProperty("m_ShortPath") != null)
                        {
                            var pathProperty = appendixSO.FindProperty("m_ShortPath");
                            if (pathProperty != null)
                            {
                                var path     = pathProperty.stringValue;
                                var contents = appendixSO.FindProperty("m_Contents");
                                outputFiles[path] = 0;
                                var totalSizeProp = appendixSO.FindProperty("m_Overhead");
                                if (totalSizeProp != null)
                                {
                                    outputFiles[path] = totalSizeProp.intValue;
                                }
                                if (contents != null)
                                {
                                    for (int j = 0; j < contents.arraySize; j++)
                                    {
                                        var entry         = contents.GetArrayElementAtIndex(j);
                                        var entryPathProp = entry.FindPropertyRelative("buildTimeAssetPath");
                                        if (entryPathProp != null)
                                        {
                                            var entryPath = entryPathProp.stringValue;
                                            if (!string.IsNullOrEmpty(entryPath))
                                            {
                                                AssetEntry assetEntry = new AssetEntry();
                                                var        asset      = AssetImporter.GetAtPath(entryPath);
                                                var        type       = asset != null?asset.GetType().Name : "Unknown";

                                                if (type.EndsWith("Importer"))
                                                {
                                                    type = type.Substring(0, type.Length - 8);
                                                }
                                                var sizeProp = entry.FindPropertyRelative("packedSize");
                                                if (!assetTypes.ContainsKey(type))
                                                {
                                                    assetTypes[type] = 0;
                                                }
                                                if (sizeProp != null)
                                                {
                                                    assetEntry.size    = sizeProp.intValue;
                                                    outputFiles[path] += sizeProp.intValue;
                                                    assetTypes[type]  += sizeProp.intValue;
                                                }
                                                assetEntry.icon       = AssetDatabase.GetCachedIcon(entryPath);
                                                assetEntry.outputFile = path;
                                                assetEntry.type       = type;
                                                assetEntry.path       = entryPath;
                                                assets.Add(assetEntry);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                assets      = assets.OrderBy(p => - p.size).ToList();
                outputFiles = outputFiles.OrderBy(p => - p.Value).ToDictionary(x => x.Key, x => x.Value);
                assetTypes  = assetTypes.OrderBy(p => - p.Value).ToDictionary(x => x.Key, x => x.Value);
            }
            switch (sourceDispMode)
            {
            case SourceAssetsDisplayMode.Size:
                ShowAssets(assets, ref vPos);
                break;

            case SourceAssetsDisplayMode.OutputDataFiles:
                foreach (var outputFile in outputFiles)
                {
                    if (!assetsFoldout.ContainsKey(outputFile.Key))
                    {
                        assetsFoldout[outputFile.Key] = false;
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    assetsFoldout[outputFile.Key] = EditorGUILayout.Foldout(assetsFoldout[outputFile.Key], outputFile.Key, DataFileStyle);
                    GUILayout.Label(FormatSize(outputFile.Value), sizeStyle);
                    GUILayout.EndHorizontal();

                    vPos += kLineHeight;

                    if (assetsFoldout[outputFile.Key])
                    {
                        ShowAssets(assets, ref vPos, outputFile.Key);
                    }
                }
                break;

            case SourceAssetsDisplayMode.ImporterType:
                foreach (var outputFile in assetTypes)
                {
                    if (!assetsFoldout.ContainsKey(outputFile.Key))
                    {
                        assetsFoldout[outputFile.Key] = false;
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(10);
                    assetsFoldout[outputFile.Key] = EditorGUILayout.Foldout(assetsFoldout[outputFile.Key], outputFile.Key, DataFileStyle);
                    GUILayout.Label(FormatSize(outputFile.Value), sizeStyle);
                    GUILayout.EndHorizontal();

                    vPos += kLineHeight;

                    if (assetsFoldout[outputFile.Key])
                    {
                        ShowAssets(assets, ref vPos, null, outputFile.Key);
                    }
                }
                break;
            }
        }
        else
        {
            GUILayout.Label("No Appendices property found");
        }
    }
        public static void ProcessObject(Location currentLocation, Object inspectedUnityObject, Object target, EntryAddSettings addSettings, ProcessObjectReferenceHandler processReferenceCallback)
        {
            var onlyVisibleProperties = currentLocation != Location.ScriptAsset;
            var componentTraverseInfo = new SerializedObjectTraverseInfo(target, onlyVisibleProperties);

            string lastScriptPropertyName = null;

            CSTraverseTools.TraverseObjectProperties(componentTraverseInfo, (info, sp) =>
            {
                if (currentLocation == Location.ScriptAsset)
                {
                    if (sp.isArray)
                    {
                        if (sp.type == "string")
                        {
                            if (sp.propertyPath.IndexOf("m_DefaultReferences.Array.data[", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                if (sp.stringValue != null)
                                {
                                    lastScriptPropertyName = sp.stringValue;

                                    // skipping first pair item of the m_DefaultReferences array item
                                    sp.Next(false);
                                }
                            }
                        }
                    }
                }

                if (sp.propertyType == SerializedPropertyType.ObjectReference && sp.objectReferenceValue != null)
                {
                    string propertyName;

                    if (lastScriptPropertyName != null)
                    {
                        propertyName           = lastScriptPropertyName;
                        lastScriptPropertyName = string.Empty;
                    }
                    else
                    {
                        propertyName = sp.propertyPath;
                    }

                    /*if (string.Equals(propertyName, "m_Script", StringComparison.OrdinalIgnoreCase))
                     * {
                     *      propertyName = "Script source";
                     * }*/

                    addSettings.propertyPath = propertyName;

                    processReferenceCallback(inspectedUnityObject, sp.objectReferenceInstanceIDValue, addSettings);

                    /* material instance handling */

                    var material = sp.objectReferenceValue as Material;
                    if (material == null)
                    {
                        return;
                    }

                    if (currentLocation == Location.PrefabAssetGameObject)
                    {
                        if (AssetDatabase.GetAssetPath(material) != AssetDatabase.GetAssetPath(target))
                        {
                            return;
                        }
                        if (AssetDatabase.IsSubAsset(material))
                        {
                            return;
                        }
                    }
                    else
                    {
                        if (AssetDatabase.Contains(material))
                        {
                            return;
                        }
                    }

                    addSettings.prefix = "[Material Instance]";
                    addSettings.suffix = "(Main Texture)";

                    var mainTextureInstanceId = 0;
                    if (material.HasProperty(MainTextureShaderProperty))
                    {
                        var mainTexture       = material.mainTexture;
                        mainTextureInstanceId = mainTexture != null ? mainTexture.GetInstanceID() : 0;
                    }

                    processReferenceCallback(inspectedUnityObject, mainTextureInstanceId, addSettings);

                    addSettings.suffix = "(Shader)";

                    var shaderInstanceId = material.shader != null ? material.shader.GetInstanceID() : 0;
                    processReferenceCallback(inspectedUnityObject, shaderInstanceId, addSettings);

                    var materialSo = new SerializedObject(material);

                    var texEnvs = materialSo.FindProperty("m_SavedProperties.m_TexEnvs.Array");
                    if (texEnvs != null)
                    {
                        for (var k = 0; k < texEnvs.arraySize; k++)
                        {
                            var arrayItem = texEnvs.GetArrayElementAtIndex(k);
                            var fieldName = arrayItem.displayName;
                            if (fieldName == MainTexturePropertyName)
                            {
                                continue;
                            }

                            var textureProperty = arrayItem.FindPropertyRelative("second.m_Texture");
                            if (textureProperty != null)
                            {
                                if (textureProperty.propertyType == SerializedPropertyType.ObjectReference)
                                {
                                    addSettings.suffix = " (" + fieldName + ")";
                                    processReferenceCallback(inspectedUnityObject, textureProperty.objectReferenceInstanceIDValue, addSettings);
                                }
                            }
                            else
                            {
                                Debug.LogError(Maintainer.ConstructError("Can't get second.m_Texture from texEnvs at " + inspectedUnityObject.name));
                            }
                        }
                    }
                    else
                    {
                        Debug.LogError(Maintainer.ConstructError("Can't get m_SavedProperties.m_TexEnvs.Array from material instance at " + inspectedUnityObject.name));
                    }
                }

                lastScriptPropertyName = null;
            });
        }
 public GizmoContext(SerializedObject obj, VFXParameter parameter)
 {
     m_SerializedObject = obj;
     m_Parameter        = parameter;
     m_VFXPropertySheet = m_SerializedObject.FindProperty("m_PropertySheet");
 }
示例#21
0
    void OnEnable()
    {
        serObj = new SerializedObject(target);

        radius = serObj.FindProperty("radius");
        bias   = serObj.FindProperty("bias");
        bilateralDepthTolerance = serObj.FindProperty("bilateralDepthTolerance");
        zThickness              = serObj.FindProperty("zThickness");
        occlusionIntensity      = serObj.FindProperty("occlusionIntensity");
        sampleDistributionCurve = serObj.FindProperty("sampleDistributionCurve");
        colorBleedAmount        = serObj.FindProperty("colorBleedAmount");
        brightnessThreshold     = serObj.FindProperty("brightnessThreshold");
        drawDistance            = serObj.FindProperty("drawDistance");
        drawDistanceFadeSize    = serObj.FindProperty("drawDistanceFadeSize");
        reduceSelfBleeding      = serObj.FindProperty("reduceSelfBleeding");
        useDownsampling         = serObj.FindProperty("useDownsampling");
        visualizeSSAO           = serObj.FindProperty("visualizeSSAO");
        halfSampling            = serObj.FindProperty("halfSampling");
        preserveDetails         = serObj.FindProperty("preserveDetails");

        targetInstance = (SESSAO)target;
    }
示例#22
0
 private SerializedProperty SetListItem(SerializedObject serializedObject, string key, int index, string value)
 {
     return(SetListItem(serializedObject?.FindProperty(key), index, value));
 }
    void OnEnable()
    {
        serObj = new SerializedObject(target);

        mode = serObj.FindProperty("mode");

        saturation = serObj.FindProperty("saturation");

        redChannel   = serObj.FindProperty("redChannel");
        greenChannel = serObj.FindProperty("greenChannel");
        blueChannel  = serObj.FindProperty("blueChannel");

        useDepthCorrection = serObj.FindProperty("useDepthCorrection");

        zCurveChannel = serObj.FindProperty("zCurve");

        depthRedChannel   = serObj.FindProperty("depthRedChannel");
        depthGreenChannel = serObj.FindProperty("depthGreenChannel");
        depthBlueChannel  = serObj.FindProperty("depthBlueChannel");

        if (redChannel.animationCurveValue.length > 0)
        {
            redChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }
        if (greenChannel.animationCurveValue.length > 0)
        {
            greenChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }
        if (blueChannel.animationCurveValue.length > 0)
        {
            blueChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }

        if (depthRedChannel.animationCurveValue.length > 0)
        {
            depthRedChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }
        if (depthGreenChannel.animationCurveValue.length > 0)
        {
            depthGreenChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }
        if (depthBlueChannel.animationCurveValue.length > 0)
        {
            depthBlueChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }

        if (zCurveChannel.animationCurveValue.length > 0)
        {
            zCurveChannel.animationCurveValue = new AnimationCurve(new Keyframe(0, 0.0f, 1.0f, 1.0f), new Keyframe(1, 1.0f, 1.0f, 1.0f));
        }

        serObj.ApplyModifiedProperties();

        selectiveCc        = serObj.FindProperty("selectiveCc");
        selectiveFromColor = serObj.FindProperty("selectiveFromColor");
        selectiveToColor   = serObj.FindProperty("selectiveToColor");
    }
        public static void GeneratePrefabFromFBX(string fbxPath, DazFigurePlatform platform)
        {
            var fbxPrefab = AssetDatabase.LoadAssetAtPath <GameObject>(fbxPath);

            if (fbxPrefab == null)
            {
                Debug.LogWarning("no FBX model prefab found at " + fbxPath);
                return;
            }

            if (PrefabUtility.GetPrefabAssetType(fbxPrefab) != PrefabAssetType.Model)
            {
                Debug.LogWarning(fbxPath + " is not a model prefab ");
                return;
            }



            System.Reflection.MethodInfo resetPose = null;
            System.Reflection.MethodInfo xferPose  = null;

            var avatarInstance = Instantiate(fbxPrefab);

            avatarInstance.name = "AvatarInstance";

            if (AutomateMecanimAvatarMappings)
            {
                var record = new ImportEventRecord();

                ModelImporter importer = GetAtPath(fbxPath) as ModelImporter;
                if (importer)
                {
                    var description = importer.humanDescription;
                    DescribeHumanJointsForFigure(ref description, platform);

                    importer.humanDescription = description;
                    importer.avatarSetup      = ModelImporterAvatarSetup.CreateFromThisModel;

                    // Genesis 8 is modeled in A-pose, so we correct to T-pose before configuring avatar joints
                    //using Unity's internal MakePoseValid method, which does a perfect job
                    if (platform == DazFigurePlatform.Genesis8 && false)
                    {
                        //use reflection to access AvatarSetupTool;
                        var setupToolType   = Type.GetType("UnityEditor.AvatarSetupTool,UnityEditor.dll");
                        var boneWrapperType = Type.GetType("UnityEditor.AvatarSetupTool+BoneWrapper,UnityEditor.dll");

                        if (boneWrapperType != null && setupToolType != null)
                        {
                            var existingMappings = new Dictionary <string, string>();
                            var human            = description.human;

                            for (var i = 0; i < human.Length; ++i)
                            {
                                existingMappings[human[i].humanName] = human[i].boneName;
                            }

                            var getModelBones = setupToolType.GetMethod("GetModelBones");
                            var getHumanBones = setupToolType.GetMethod("GetHumanBones", new[] { typeof(Dictionary <string, string>), typeof(Dictionary <Transform, bool>) });
                            var makePoseValid = setupToolType.GetMethod("MakePoseValid");
                            resetPose = setupToolType.GetMethod("CopyPose");
                            xferPose  = setupToolType.GetMethod("TransferPoseToDescription");

                            if (getModelBones != null && getHumanBones != null && makePoseValid != null)
                            {
                                record.AddToken("Corrected Avatar Setup T-pose for Genesis8 figure: ", null);
                                record.AddToken(fbxPrefab.name, fbxPrefab, ENDLINE);

                                var modelBones = (Dictionary <Transform, bool>)getModelBones.Invoke(null, new object[] { avatarInstance.transform, false, null });
                                var humanBones = (ICollection <object>)getHumanBones.Invoke(null, new object[] { existingMappings, modelBones });

                                // a little dance to populate array of Unity's internal BoneWrapper type
                                var humanBonesArray = new object[humanBones.Count];
                                humanBones.CopyTo(humanBonesArray, 0);
                                Array destinationArray = Array.CreateInstance(boneWrapperType, humanBones.Count);
                                Array.Copy(humanBonesArray, destinationArray, humanBones.Count);

                                //This mutates the transforms (modelBones) via Bonewrapper class
                                makePoseValid.Invoke(null, new[] { destinationArray });
                            }
                        }
                    }

                    AssetDatabase.WriteImportSettingsIfDirty(fbxPath);
                    AssetDatabase.ImportAsset(fbxPath, ImportAssetOptions.ForceUpdate);


                    // i think this might unT-pose the gen8 skeleton instance
                    if (resetPose != null && xferPose != null)
                    {
                        SerializedObject modelImporterObj = new SerializedObject(importer);
                        var skeleton = modelImporterObj?.FindProperty("m_HumanDescription.m_Skeleton");

                        if (skeleton != null)
                        {
                            resetPose.Invoke(null, new object[] { avatarInstance, fbxPrefab });
                            //xferPose.Invoke(null, new object[] { skeleton, avatarInstance.transform });
                        }
                    }

                    DestroyImmediate(avatarInstance);

                    record.AddToken("Automated Mecanim avatar setup for " + fbxPrefab.name + ": ");

                    //a little dance to get the avatar just reimported
                    var allAvatars = Resources.FindObjectsOfTypeAll(typeof(Avatar));
                    var avatar     = Array.Find(allAvatars, element => element.name.StartsWith(fbxPrefab.name));
                    if (avatar)
                    {
                        record.AddToken(avatar.name, avatar, ENDLINE);
                    }
                }
                else
                {
                    Debug.LogWarning("Could not acquire importer for " + fbxPath + " ...could not automatically configure humanoid avatar.");
                    record.AddToken("Could not acquire importer for " + fbxPath + " ...could not automatically configure humanoid avatar.", null, ENDLINE);
                }

                EventQueue.Enqueue(record);
            }


            //remap the materials
            var workingInstance = Instantiate(fbxPrefab);

            workingInstance.name = "Daz3d_" + fbxPrefab.name;

            var renderers = workingInstance.GetComponentsInChildren <Renderer>();

            if (renderers?.Length == 0)
            {
                Debug.LogWarning("no renderers found for material remapping");
                return;
            }

            var modelPath = AssetDatabase.GetAssetPath(fbxPrefab);

            if (ReplaceMaterials)
            {
                foreach (var renderer in renderers)
                {
                    var dict = new Dictionary <Material, Material>();

                    if (renderer.name.ToLower().Contains("eyelashes"))
                    {
                        renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
                    }
                    foreach (var keyMat in renderer.sharedMaterials)
                    {
                        var key = keyMat.name;

                        key = Daz3D.Utilities.ScrubKey(key);

                        Material nuMat = null;

                        if (_map != null && _map.Map.ContainsKey(key))
                        {
                            nuMat = _map.Map[key];// the preferred uber/iRay based material generated by the DTUConverter
                        }
                        else if (s_StandardMaterialCollection.ContainsKey(key))
                        {
                            nuMat = new Material(s_StandardMaterialCollection[key]);
                            //FixupStandardBasedMaterial(ref nuMat, fbxPrefab, keyMat.name, data);
                        }
                        else
                        {
                            var shader = Shader.Find("HDRP/Lit");

                            if (shader == null)
                            {
                                Debug.LogWarning("couldn't find HDRP/Lit shader");
                                continue;
                            }

                            nuMat = new Material(shader);
                            nuMat.CopyPropertiesFromMaterial(keyMat);

                            // just copy the textures, colors and scalars that are appropriate given the base material type
                            //DazMaterialPropertiesInfo info = new DazMaterialPropertiesInfo();
                            //CustomizeMaterial(ref nuMat, info);

                            var matPath = Path.GetDirectoryName(modelPath);
                            matPath = Path.Combine(matPath, fbxPrefab.name + "Daz3D_Materials");
                            matPath = AssetDatabase.GenerateUniqueAssetPath(matPath);

                            if (!Directory.Exists(matPath))
                            {
                                Directory.CreateDirectory(matPath);
                            }

                            //Debug.Log("obj path " + path);
                            AssetDatabase.CreateAsset(nuMat, matPath + "/Daz3D_" + keyMat.name + ".mat");
                        }

                        dict.Add(keyMat, nuMat);
                    }

                    //remap the meshes in the fbx prefab to the value materials in dict
                    var count = renderer.sharedMaterials.Length;
                    var copy  = new Material[count]; //makes a copy
                    for (int i = 0; i < count; i++)
                    {
                        var key = renderer.sharedMaterials[i];
                        //Debug.Log("remapping: " + renderer.sharedMaterials[i].name + " to " + dict[key].name);
                        copy[i] = dict[key];//fill copy
                    }

                    renderer.sharedMaterials = copy;//overwrite sharedMaterials, because set indexer assigns to a copy
                }
            }

            //write the prefab to the asset database
            // Make sure the file name is unique, in case an existing Prefab has the same name.
            var nuPrefabPathPath = Path.GetDirectoryName(modelPath);

            nuPrefabPathPath = Path.Combine(nuPrefabPathPath, fbxPrefab.name + "_Prefab");
            nuPrefabPathPath = AssetDatabase.GenerateUniqueAssetPath(nuPrefabPathPath);
            if (!Directory.Exists(nuPrefabPathPath))
            {
                Directory.CreateDirectory(nuPrefabPathPath);
            }

            nuPrefabPathPath += "/Daz3D_" + fbxPrefab.name + ".prefab";

            // For future refreshment
            var component = workingInstance.AddComponent <Daz3DInstance>();

            component.SourceFBX = fbxPrefab;

            // Create the new Prefab.
            var prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(workingInstance, nuPrefabPathPath, InteractionMode.AutomatedAction);

            Selection.activeGameObject = prefab;

            //now, seek other instance(s) in the scene having been sourced from this fbx asset
            var otherInstances = FindObjectsOfType <Daz3DInstance>();
            int foundCount     = 0;

            var resultingInstance = workingInstance;

            if (ReplaceSceneInstances)
            {
                foreach (var otherInstance in otherInstances)
                {
                    if (otherInstance == component)//ignore this working instance
                    {
                        continue;
                    }
                    if (otherInstance.SourceFBX != fbxPrefab)//ignore instances of other assets
                    {
                        continue;
                    }


                    //for any found that flag ReplaceOnImport, delete that instance and replace with a copy of
                    //this one, at their respective transforms
                    if (otherInstance.ReplaceOnImport)
                    {
                        foundCount++;
                        var xform = otherInstance.transform;
                        var replacementInstance = PrefabUtility.InstantiatePrefab(prefab, xform.parent) as GameObject;
                        replacementInstance.transform.position = xform.position;
                        replacementInstance.transform.rotation = xform.rotation;
                        //var replacementInstance = Instantiate(prefab, xform.position, xform.rotation, xform.parent);
                        //PrefabUtility.RevertPrefabInstance(replacementInstance, InteractionMode.AutomatedAction);
                        DestroyImmediate(otherInstance.gameObject);
                        resultingInstance = replacementInstance;
                    }
                }
            }

            //if no prior instances found, then don't destroy this instance
            //since it appears to be the first one to arrive
            if (foundCount > 0)
            {
                DestroyImmediate(workingInstance);
            }


            ImportEventRecord pfbRecord = new ImportEventRecord();

            pfbRecord.AddToken("Created Unity Prefab: ");
            pfbRecord.AddToken(prefab.name, prefab);
            pfbRecord.AddToken(" and an instance in the scene: ");
            pfbRecord.AddToken(resultingInstance.name, resultingInstance, ENDLINE);
            EventQueue.Enqueue(pfbRecord);

            //highlight/select the object in the scene view
            Selection.activeGameObject = resultingInstance;
        }
示例#25
0
    void OnGUI()
    {
        GUILayout.Label(position + "");
        GUILayout.Space(3);
        int oldValue = GUI.skin.window.padding.bottom;

        GUI.skin.window.padding.bottom = -20;
        Rect windowRect = GUILayoutUtility.GetRect(1, 17);

        windowRect.x     += 4;
        windowRect.width -= 7;
        editorMode        = GUI.SelectionGrid(windowRect, editorMode, modes, 2, "Window");
        GUI.skin.window.padding.bottom = oldValue;

        switch (editorMode)
        {
        case 0:
            selectedCheckType = GUILayout.SelectionGrid(selectedCheckType, checkType, 2, "Toggle");
            GUI.enabled       = selectedCheckType == 0;
            targetComponent   = (MonoScript)EditorGUILayout.ObjectField(targetComponent, typeof(MonoScript), false);
            GUI.enabled       = true;

            if (GUILayout.Button("Check component usage"))
            {
                AssetDatabase.SaveAssets();
                switch (selectedCheckType)
                {
                case 0:
                    componentName = targetComponent.name;
                    string   targetPath = AssetDatabase.GetAssetPath(targetComponent);
                    string[] allPrefabs = GetAllPrefabs();
                    listResult = new List <string>();
                    foreach (string prefab in allPrefabs)
                    {
                        string[] single       = new string[] { prefab };
                        string[] dependencies = AssetDatabase.GetDependencies(single);
                        foreach (string dependedAsset in dependencies)
                        {
                            if (dependedAsset == targetPath)
                            {
                                listResult.Add(prefab);
                            }
                        }
                    }
                    break;

                case 1:
                    List <string> scenesToLoad = new List <string>();
                    existingComponents = new List <ComponentNames>();
                    prefabComponents   = new List <ComponentNames>();
                    notUsedComponents  = new List <ComponentNames>();
                    addedComponents    = new List <ComponentNames>();
                    sceneComponents    = new List <ComponentNames>();

                    if (EditorApplication.SaveCurrentSceneIfUserWantsTo())
                    {
                        string projectPath = Application.dataPath;
                        projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets"));

                        string[] allAssets = AssetDatabase.GetAllAssetPaths();

                        foreach (string asset in allAssets)
                        {
                            int indexCS = asset.IndexOf(".cs");
                            int indexJS = asset.IndexOf(".js");
                            if (indexCS != -1 || indexJS != -1)
                            {
                                ComponentNames newComponent = new ComponentNames(NameFromPath(asset), "", asset);
                                try
                                {
                                    System.IO.FileStream   FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                                    System.IO.StreamReader SR = new System.IO.StreamReader(FS);
                                    string line;
                                    while (!SR.EndOfStream)
                                    {
                                        line = SR.ReadLine();
                                        int index1 = line.IndexOf("namespace");
                                        int index2 = line.IndexOf("{");
                                        if (index1 != -1 && index2 != -1)
                                        {
                                            line   = line.Substring(index1 + 9);
                                            index2 = line.IndexOf("{");
                                            line   = line.Substring(0, index2);
                                            line   = line.Replace(" ", "");
                                            newComponent.namespaceName = line;
                                        }
                                    }
                                }
                                catch
                                {
                                }

                                existingComponents.Add(newComponent);

                                try
                                {
                                    System.IO.FileStream   FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                                    System.IO.StreamReader SR = new System.IO.StreamReader(FS);

                                    string line;
                                    int    lineNum = 0;
                                    while (!SR.EndOfStream)
                                    {
                                        lineNum++;
                                        line = SR.ReadLine();
                                        int index = line.IndexOf("AddComponent");
                                        if (index != -1)
                                        {
                                            line = line.Substring(index + 12);
                                            if (line[0] == '(')
                                            {
                                                line = line.Substring(1, line.IndexOf(')') - 1);
                                            }
                                            else if (line[0] == '<')
                                            {
                                                line = line.Substring(1, line.IndexOf('>') - 1);
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                            line  = line.Replace(" ", "");
                                            line  = line.Replace("\"", "");
                                            index = line.LastIndexOf('.');
                                            ComponentNames newComp;
                                            if (index == -1)
                                            {
                                                newComp = new ComponentNames(line, "", "");
                                            }
                                            else
                                            {
                                                newComp = new ComponentNames(line.Substring(index + 1, line.Length - (index + 1)), line.Substring(0, index), "");
                                            }
                                            string pName = asset + ", Line " + lineNum;
                                            newComp.usageSource.Add(pName);
                                            index = addedComponents.IndexOf(newComp);
                                            if (index == -1)
                                            {
                                                addedComponents.Add(newComp);
                                            }
                                            else
                                            {
                                                if (!addedComponents[index].usageSource.Contains(pName))
                                                {
                                                    addedComponents[index].usageSource.Add(pName);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                            int indexPrefab = asset.IndexOf(".prefab");

                            if (indexPrefab != -1)
                            {
                                string[] single       = new string[] { asset };
                                string[] dependencies = AssetDatabase.GetDependencies(single);
                                foreach (string dependedAsset in dependencies)
                                {
                                    if (dependedAsset.IndexOf(".cs") != -1 || dependedAsset.IndexOf(".js") != -1)
                                    {
                                        ComponentNames newComponent = new ComponentNames(NameFromPath(dependedAsset), GetNamespaceFromPath(dependedAsset), dependedAsset);
                                        int            index        = prefabComponents.IndexOf(newComponent);
                                        if (index == -1)
                                        {
                                            newComponent.usageSource.Add(asset);
                                            prefabComponents.Add(newComponent);
                                        }
                                        else
                                        {
                                            if (!prefabComponents[index].usageSource.Contains(asset))
                                            {
                                                prefabComponents[index].usageSource.Add(asset);
                                            }
                                        }
                                    }
                                }
                            }
                            int indexUnity = asset.IndexOf(".unity");
                            if (indexUnity != -1)
                            {
                                scenesToLoad.Add(asset);
                            }
                        }

                        for (int i = addedComponents.Count - 1; i > -1; i--)
                        {
                            addedComponents[i].assetPath = GetPathFromNames(addedComponents[i].namespaceName, addedComponents[i].componentName);
                            if (addedComponents[i].assetPath == "")
                            {
                                addedComponents.RemoveAt(i);
                            }
                        }

                        foreach (string scene in scenesToLoad)
                        {
                            EditorApplication.OpenScene(scene);
                            GameObject[] sceneGOs = GetAllObjectsInScene();
                            foreach (GameObject g in sceneGOs)
                            {
                                Component[] comps = g.GetComponentsInChildren <Component>(true);
                                foreach (Component c in comps)
                                {
                                    if (c != null && c.GetType() != null && c.GetType().BaseType != null && c.GetType().BaseType == typeof(MonoBehaviour))
                                    {
                                        SerializedObject   so      = new SerializedObject(c);
                                        SerializedProperty p       = so.FindProperty("m_Script");
                                        string             path    = AssetDatabase.GetAssetPath(p.objectReferenceValue);
                                        ComponentNames     newComp = new ComponentNames(NameFromPath(path), GetNamespaceFromPath(path), path);
                                        newComp.usageSource.Add(scene);
                                        int index = sceneComponents.IndexOf(newComp);
                                        if (index == -1)
                                        {
                                            sceneComponents.Add(newComp);
                                        }
                                        else
                                        {
                                            if (!sceneComponents[index].usageSource.Contains(scene))
                                            {
                                                sceneComponents[index].usageSource.Add(scene);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        foreach (ComponentNames c in existingComponents)
                        {
                            if (addedComponents.Contains(c))
                            {
                                continue;
                            }
                            if (prefabComponents.Contains(c))
                            {
                                continue;
                            }
                            if (sceneComponents.Contains(c))
                            {
                                continue;
                            }
                            notUsedComponents.Add(c);
                        }

                        addedComponents.Sort(SortAlphabetically);
                        prefabComponents.Sort(SortAlphabetically);
                        sceneComponents.Sort(SortAlphabetically);
                        notUsedComponents.Sort(SortAlphabetically);
                    }
                    break;
                }
            }
            break;

        case 1:
            if (GUILayout.Button("Search!"))
            {
                string[] allPrefabs = GetAllPrefabs();
                listResult = new List <string>();
                foreach (string prefab in allPrefabs)
                {
                    UnityEngine.Object o = AssetDatabase.LoadMainAssetAtPath(prefab);
                    GameObject         go;
                    try
                    {
                        go = (GameObject)o;
                        Component[] components = go.GetComponentsInChildren <Component>(true);
                        foreach (Component c in components)
                        {
                            if (c == null)
                            {
                                listResult.Add(prefab);
                            }
                        }
                    }
                    catch
                    {
                        Debug.Log("For some reason, prefab " + prefab + " won't cast to GameObject");
                    }
                }
            }
            break;
        }
        if (editorMode == 1 || selectedCheckType == 0)
        {
            if (listResult != null)
            {
                if (listResult.Count == 0)
                {
                    GUILayout.Label(editorMode == 0 ? (componentName == "" ? "Choose a component" : "No prefabs use component " + componentName) : ("No prefabs have missing components!\nClick Search to check again"));
                }
                else
                {
                    GUILayout.Label(editorMode == 0 ? ("The following prefabs use component " + componentName + ":") : ("The following prefabs have missing components:"));
                    scroll = GUILayout.BeginScrollView(scroll);
                    foreach (string s in listResult)
                    {
                        GUILayout.BeginHorizontal();
                        GUILayout.Label(s, GUILayout.Width(position.width / 2));
                        if (GUILayout.Button("Select", GUILayout.Width(position.width / 2 - 10)))
                        {
                            Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(s);
                        }
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndScrollView();
                }
            }
        }
        else
        {
            showPrefabs = GUILayout.Toggle(showPrefabs, "Show prefab components");
            if (showPrefabs)
            {
                GUILayout.Label("The following components are attatched to prefabs:");
                DisplayResults(ref scroll1, ref prefabComponents);
            }
            showAdded = GUILayout.Toggle(showAdded, "Show AddComponent arguments");
            if (showAdded)
            {
                GUILayout.Label("The following components are AddComponent arguments:");
                DisplayResults(ref scroll2, ref addedComponents);
            }
            showScene = GUILayout.Toggle(showScene, "Show Scene-used components");
            if (showScene)
            {
                GUILayout.Label("The following components are used by scene objects:");
                DisplayResults(ref scroll3, ref sceneComponents);
            }
            showUnused = GUILayout.Toggle(showUnused, "Show Unused Components");
            if (showUnused)
            {
                GUILayout.Label("The following components are not used by prefabs, by AddComponent, OR in any scene:");
                DisplayResults(ref scroll4, ref notUsedComponents);
            }
        }
    }
示例#26
0
    public override void OnInspectorGUI()
    {
        ServerSettings settings = (ServerSettings)target;


        settings.HostType     = (ServerSettings.HostingOption)EditorGUILayout.EnumPopup("Hosting", settings.HostType);
        EditorGUI.indentLevel = 1;

        switch (settings.HostType)
        {
        case ServerSettings.HostingOption.BestRegion:
        case ServerSettings.HostingOption.PhotonCloud:
            // region selection
            if (settings.HostType == ServerSettings.HostingOption.PhotonCloud)
            {
                settings.PreferredRegion = (CloudRegionCode)EditorGUILayout.EnumPopup("Region", settings.PreferredRegion);
            }
            else
            {
                CloudRegionFlag valRegions = (CloudRegionFlag)EditorGUILayout.EnumMaskField("Enabled Regions", settings.EnabledRegions);

                if (valRegions != settings.EnabledRegions)
                {
                    settings.EnabledRegions = valRegions;
                    this.showMustHaveRegion = valRegions == 0;
                }
                if (this.showMustHaveRegion)
                {
                    EditorGUILayout.HelpBox("You should enable at least two regions for 'Best Region' hosting.", MessageType.Warning);
                }
            }

            // appid
            string valAppId = EditorGUILayout.TextField("AppId", settings.AppID);
            if (valAppId != settings.AppID)
            {
                settings.AppID     = valAppId;
                this.showAppIdHint = !IsAppId(settings.AppID);
            }
            if (this.showAppIdHint)
            {
                EditorGUILayout.HelpBox("The Photon Cloud needs an AppId (GUID) set.\nYou can find it online in your Dashboard.", MessageType.Warning);
            }

            // protocol
            ProtocolChoices valProtocol = settings.Protocol == ConnectionProtocol.Tcp ? ProtocolChoices.Tcp : ProtocolChoices.Udp;
            valProtocol       = (ProtocolChoices)EditorGUILayout.EnumPopup("Protocol", valProtocol);
            settings.Protocol = (ConnectionProtocol)valProtocol;
                #if UNITY_WEBGL
            EditorGUILayout.HelpBox("WebGL always use Secure WebSockets as protocol.\nThis setting gets ignored in current export.", MessageType.Warning);
                #endif
            break;

        case ServerSettings.HostingOption.SelfHosted:
            // address and port (depends on protocol below)
            bool hidePort = false;
            if (settings.Protocol == ConnectionProtocol.Udp && (settings.ServerPort == 4530 || settings.ServerPort == 0))
            {
                settings.ServerPort = 5055;
            }
            else if (settings.Protocol == ConnectionProtocol.Tcp && (settings.ServerPort == 5055 || settings.ServerPort == 0))
            {
                settings.ServerPort = 4530;
            }
                #if RHTTP
            if (settings.Protocol == ConnectionProtocol.RHttp)
            {
                settings.ServerPort = 0;
                hidePort            = true;
            }
                #endif
            settings.ServerAddress = EditorGUILayout.TextField("Server Address", settings.ServerAddress);
            settings.ServerAddress = settings.ServerAddress.Trim();
            if (!hidePort)
            {
                settings.ServerPort = EditorGUILayout.IntField("Server Port", settings.ServerPort);
            }

            // protocol
            valProtocol       = settings.Protocol == ConnectionProtocol.Tcp ? ProtocolChoices.Tcp : ProtocolChoices.Udp;
            valProtocol       = (ProtocolChoices)EditorGUILayout.EnumPopup("Protocol", valProtocol);
            settings.Protocol = (ConnectionProtocol)valProtocol;
                #if UNITY_WEBGL
            EditorGUILayout.HelpBox("WebGL always use Secure WebSockets as protocol.\nThis setting gets ignored in current export.", MessageType.Warning);
                #endif

            // appid
            settings.AppID = EditorGUILayout.TextField("AppId", settings.AppID);
            break;

        case ServerSettings.HostingOption.OfflineMode:
            EditorGUI.indentLevel = 0;
            EditorGUILayout.HelpBox("In 'Offline Mode', the client does not communicate with a server.\nAll settings are hidden currently.", MessageType.Info);
            break;

        case ServerSettings.HostingOption.NotSet:
            EditorGUI.indentLevel = 0;
            EditorGUILayout.HelpBox("Hosting is 'Not Set'.\nConnectUsingSettings() will not be able to connect.\nSelect another option or run the PUN Wizard.", MessageType.Info);
            break;

        default:
            DrawDefaultInspector();
            break;
        }

        EditorGUI.indentLevel = 0;
        EditorGUILayout.LabelField("Client Settings");
        EditorGUI.indentLevel = 1;
        //EditorGUILayout.LabelField("game version");
        settings.JoinLobby             = EditorGUILayout.Toggle("Auto-Join Lobby", settings.JoinLobby);
        settings.EnableLobbyStatistics = EditorGUILayout.Toggle("Enable Lobby Stats", settings.EnableLobbyStatistics);
        //EditorGUILayout.LabelField("automaticallySyncScene");
        //EditorGUILayout.LabelField("autoCleanUpPlayerObjects");
        //EditorGUILayout.LabelField("log level");
        //EditorGUILayout.LabelField("lobby stats");
        //EditorGUILayout.LabelField("sendrate / serialize rate");
        //EditorGUILayout.LabelField("quick resends");
        //EditorGUILayout.LabelField("max resends");
        //EditorGUILayout.LabelField("enable crc checking");


        if (PhotonEditor.CheckPunPlus())
        {
            settings.Protocol = ConnectionProtocol.Udp;
            EditorGUILayout.HelpBox("You seem to use PUN+.\nPUN+ only supports reliable UDP so the protocol is locked.", MessageType.Info);
        }

        settings.AppID = settings.AppID.Trim();


        // RPC-shortcut list
        EditorGUI.indentLevel = 0;
        SerializedObject   sObj  = new SerializedObject(target);
        SerializedProperty sRpcs = sObj.FindProperty("RpcList");
        EditorGUILayout.PropertyField(sRpcs, true);
        sObj.ApplyModifiedProperties();

        GUILayout.BeginHorizontal();
        GUILayout.Space(20);
        if (GUILayout.Button("Refresh RPCs"))
        {
            PhotonEditor.UpdateRpcList();
            Repaint();
        }
        if (GUILayout.Button("Clear RPCs"))
        {
            PhotonEditor.ClearRpcList();
        }
        if (GUILayout.Button("Log HashCode"))
        {
            Debug.Log("RPC-List HashCode: " + RpcListHashCode() + ". Make sure clients that send each other RPCs have the same RPC-List.");
        }
        GUILayout.Space(20);
        GUILayout.EndHorizontal();

        //SerializedProperty sp = serializedObject.FindProperty("RpcList");
        //EditorGUILayout.PropertyField(sp, true);

        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
		public override void OnFlowWindowScreenMenuGUI(FD.FlowWindow windowSource, GenericMenu menu) {

			menu.AddItem(new GUIContent("Components Editor..."), on: false, func: (object win) => {

				var window = win as FD.FlowWindow;
				var screen = window.GetScreen() as LayoutWindowType;
				if (screen != null) {

					FlowSystemEditorWindow.GetWindow<FlowSystemEditorWindow>().SetDisabled();
					//this.window = window;
					this.screen = screen;
					this.editor = Editor.CreateEditor(window.GetScreen()) as IPreviewEditor;
					
					this.component = null;
					this.hovered = null;
					this.element = null;
					this.listScrollPosition = Vector2.zero;
					var serializedObject = new SerializedObject(this.screen);
					var layout = serializedObject.FindProperty("layout");
					var components = layout.FindPropertyRelative("components");
					this.props.Clear();
					for (int i = 0; i < components.arraySize; ++i) {
						
						var component = components.GetArrayElementAtIndex(i);
						this.props.Add(component);
						
						this.screen.layout.components[i].OnComponentChanged(this.screen, this.screen.layout.components[i].component);
						
					}
					
					this.settingsScrollPosition = Vector2.zero;
					
					this.opened = true;

				}

			}, userData: windowSource);

		}
 private void FindProperties()
 {
     inputFiles          = serializedSettings.FindProperty(nameof(TreeImportSettings.inputFiles));
     outputPath          = serializedSettings.FindProperty(nameof(TreeImportSettings.outputPath));
     treeType            = serializedSettings.FindProperty(nameof(TreeImportSettings.treeType));
     sampling            = serializedSettings.FindProperty(nameof(TreeImportSettings.sampling));
     rootNodeSubdivision = serializedSettings.FindProperty(nameof(TreeImportSettings.rootNodeSubdivision));
     nodeBranchThreshold = serializedSettings.FindProperty(nameof(TreeImportSettings.nodeBranchThreshold));
     maxTreeDepth        = serializedSettings.FindProperty(nameof(TreeImportSettings.maxTreeDepth));
     threadCount         = serializedSettings.FindProperty(nameof(TreeImportSettings.threadCount));
     chunkSize           = serializedSettings.FindProperty(nameof(TreeImportSettings.chunkSize));
     center               = serializedSettings.FindProperty(nameof(TreeImportSettings.center));
     normalize            = serializedSettings.FindProperty(nameof(TreeImportSettings.normalize));
     lasRGB8BitWorkaround = serializedSettings.FindProperty(nameof(TreeImportSettings.lasRGB8BitWorkaround));
     axes = serializedSettings.FindProperty(nameof(TreeImportSettings.axes));
 }
示例#29
0
        /// <summary>
        /// Implement this function to make a custom inspector.
        /// </summary>
        public override void OnInspectorGUI()
        {
            foreach (var d in targets.Cast <UIDissolve> ())
            {
                var mat = d.material;
                if (d.isTMPro && mat && mat.HasProperty(s_NoiseTexId))
                {
                    ColorMode colorMode =
                        mat.IsKeywordEnabled("ADD") ? ColorMode.Add
                                                                                : mat.IsKeywordEnabled("SUBTRACT") ? ColorMode.Subtract
                                                                                : mat.IsKeywordEnabled("FILL") ? ColorMode.Fill
                                                                                : ColorMode.Multiply;

                    Texture noiseTexture = mat.GetTexture(s_NoiseTexId);

                    if (d.colorMode != colorMode || d.noiseTexture != noiseTexture)
                    {
                        var so = new SerializedObject(d);
                        so.FindProperty("m_ColorMode").intValue = (int)colorMode;
                        so.FindProperty("m_NoiseTexture").objectReferenceValue = noiseTexture;
                        so.ApplyModifiedProperties();
                    }
                }
            }

            serializedObject.Update();

            //================
            // Effect material.
            //================
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.PropertyField(_spMaterial);
            EditorGUI.EndDisabledGroup();

            //================
            // Effect setting.
            //================
            EditorGUILayout.PropertyField(_spEffectFactor);
            EditorGUILayout.PropertyField(_spWidth);
            EditorGUILayout.PropertyField(_spSoftness);
            EditorGUILayout.PropertyField(_spColor);

            using (new EditorGUI.DisabledGroupScope((target as UIDissolve).isTMPro))
            {
                EditorGUILayout.PropertyField(_spColorMode);
                EditorGUILayout.PropertyField(_spNoiseTexture);
            }

            //================
            // Advanced option.
            //================
            GUILayout.Space(10);
            EditorGUILayout.LabelField("Advanced Option", EditorStyles.boldLabel);

            EditorGUILayout.PropertyField(_spEffectArea);
            EditorGUILayout.PropertyField(_spKeepAspectRatio);

            //================
            // Effect runner.
            //================
            GUILayout.Space(10);
            EditorGUILayout.LabelField("Effect Player", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(_spDuration);
            EditorGUILayout.PropertyField(_spUpdateMode);

            // Debug.
            using (new EditorGUI.DisabledGroupScope(!Application.isPlaying))
                using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox))
                {
                    GUILayout.Label("Debug");

                    if (GUILayout.Button("Play", "ButtonLeft"))
                    {
                        (target as UIDissolve).Play();
                    }

                    if (GUILayout.Button("Stop", "ButtonRight"))
                    {
                        (target as UIDissolve).Stop();
                    }
                }

            var c = target as UIDissolve;

            c.ShowTMProWarning(_shader, _mobileShader, _spriteShader, mat => {
                if (mat.shader == _spriteShader)
                {
                    mat.shaderKeywords = c.material.shaderKeywords;
                    mat.SetTexture("_NoiseTex", c.material.GetTexture("_NoiseTex"));
                }
            });
            ShowCanvasChannelsWarning();

            ShowMaterialEditors(c.materials, 1, c.materials.Length - 1);

            serializedObject.ApplyModifiedProperties();
        }
示例#30
0
 protected override void FixOceanFeatureDisabled(SerializedObject oceanComponent)
 {
     oceanComponent.FindProperty("_createClipSurfaceData").boolValue = true;
 }
 SerializedProperty GetProperty(string propName) => SerializedObject?.FindProperty(propName);
示例#32
0
 public MarsTimeModuleDrawer(SerializedObject serializedObject)
 {
     m_TimeStep = serializedObject.FindProperty("m_TimeStep");
 }