예제 #1
0
        public static void convert(MenuCommand command)
        {
            var graphicRenderer = (command.context as MeshRenderer).GetComponentInParent <LeapGraphicRenderer>();

            if (graphicRenderer.groups.Count == 0)
            {
                graphicRenderer.editor.CreateGroup(typeof(LeapBakedRenderer));
            }

            var group = graphicRenderer.groups[0];

            var graphics      = new List <LeapMeshGraphic>();
            var meshRenderers = (command.context as MeshRenderer).GetComponentsInChildren <MeshRenderer>();

            foreach (var meshRenderer in meshRenderers)
            {
                var material = meshRenderer.sharedMaterial;
                if (material == null)
                {
                    continue;
                }

                var shader = material.shader;
                if (shader == null)
                {
                    continue;
                }

                var filter = meshRenderer.GetComponent <MeshFilter>();
                if (filter == null)
                {
                    continue;
                }

                var mesh = filter.sharedMesh;
                if (mesh == null)
                {
                    continue;
                }

                int propCount = ShaderUtil.GetPropertyCount(shader);
                for (int i = 0; i < propCount; i++)
                {
                    if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
                    {
                        string propName = ShaderUtil.GetPropertyName(shader, i);

                        if (material.GetTexture(propName) == null)
                        {
                            continue;
                        }

                        var feature = group.features.Query().
                                      OfType <LeapTextureFeature>().
                                      FirstOrDefault(f => f.propertyName == propName);

                        if (feature == null)
                        {
                            feature              = group.editor.AddFeature(typeof(LeapTextureFeature)) as LeapTextureFeature;
                            feature.channel      = UnityEngine.Rendering.UVChannelFlags.UV0;
                            feature.propertyName = propName;
                        }
                    }
                }

                var graphic = meshRenderer.gameObject.AddComponent <LeapMeshGraphic>();
                Undo.RegisterCreatedObjectUndo(graphic, "Create Leap Mesh Graphic");

                group.TryAddGraphic(graphic);
                graphics.Add(graphic);
            }

            foreach (var graphic in graphics)
            {
                var meshRenderer = graphic.GetComponent <MeshRenderer>();
                var meshFilter   = graphic.GetComponent <MeshFilter>();
                var material     = meshRenderer.sharedMaterial;

                graphic.SetMesh(meshFilter.sharedMesh);

                foreach (var dataObj in graphic.featureData)
                {
                    var textureData = dataObj as LeapTextureData;
                    if (textureData == null)
                    {
                        continue;
                    }

                    var feature = textureData.feature as LeapTextureFeature;
                    if (!material.HasProperty(feature.propertyName))
                    {
                        continue;
                    }

                    Texture2D tex2d = material.GetTexture(feature.propertyName) as Texture2D;
                    if (tex2d == null)
                    {
                        continue;
                    }

                    textureData.texture = tex2d;
                }

                Undo.DestroyObjectImmediate(meshRenderer);
                Undo.DestroyObjectImmediate(meshFilter);
            }

            group.renderer.editor.ScheduleRebuild();
        }
예제 #2
0
        void SetupChildList()
        {
            float vSpace          = 2;
            float hSpace          = 3;
            float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f;

            mChildList = new UnityEditorInternal.ReorderableList(
                serializedObject, FindProperty(x => x.m_ChildCameras), true, true, true, true);

            mChildList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Virtual Camera Children");
                GUIContent priorityText   = new GUIContent("Priority");
                var        textDimensions = GUI.skin.label.CalcSize(priorityText);
                rect.x    += rect.width - textDimensions.x;
                rect.width = textDimensions.x;
                EditorGUI.LabelField(rect, priorityText);
            };
            mChildList.drawElementCallback
                = (Rect rect, int index, bool isActive, bool isFocused) =>
                {
                rect.y     += vSpace;
                rect.width -= floatFieldWidth + hSpace;
                rect.height = EditorGUIUtility.singleLineHeight;
                SerializedProperty element = mChildList.serializedProperty.GetArrayElementAtIndex(index);
                if (m_ColliderState == ColliderState.ColliderOnSomeChildren ||
                    m_ColliderState == ColliderState.ColliderOnChildrenAndParent)
                {
                    bool hasCollider = ObjectHasCollider(element.objectReferenceValue);
                    if ((m_ColliderState == ColliderState.ColliderOnSomeChildren && !hasCollider) ||
                        (m_ColliderState == ColliderState.ColliderOnChildrenAndParent && hasCollider))
                    {
                        float width = rect.width;
                        rect.width = rect.height;
                        GUIContent label = new GUIContent("");
                        label.image = EditorGUIUtility.IconContent("console.warnicon.sml").image;
                        EditorGUI.LabelField(rect, label);
                        width -= rect.width; rect.x += rect.width; rect.width = width;
                    }
                }
                EditorGUI.PropertyField(rect, element, GUIContent.none);

                SerializedObject obj = new SerializedObject(element.objectReferenceValue);
                rect.x += rect.width + hSpace; rect.width = floatFieldWidth;
                SerializedProperty priorityProp = obj.FindProperty(() => Target.m_Priority);
                float oldWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = hSpace * 2;
                EditorGUI.PropertyField(rect, priorityProp, new GUIContent(" "));
                EditorGUIUtility.labelWidth = oldWidth;
                obj.ApplyModifiedProperties();
                };
            mChildList.onChangedCallback = (UnityEditorInternal.ReorderableList l) =>
            {
                if (l.index < 0 || l.index >= l.serializedProperty.arraySize)
                {
                    return;
                }
                Object o = l.serializedProperty.GetArrayElementAtIndex(
                    l.index).objectReferenceValue;
                CinemachineVirtualCameraBase vcam = (o != null)
                        ? (o as CinemachineVirtualCameraBase) : null;
                if (vcam != null)
                {
                    vcam.transform.SetSiblingIndex(l.index);
                }
            };
            mChildList.onAddCallback = (UnityEditorInternal.ReorderableList l) =>
            {
                var index = l.serializedProperty.arraySize;
                var vcam  = CinemachineMenu.CreateDefaultVirtualCamera();
                Undo.SetTransformParent(vcam.transform, Target.transform, "");
                var collider = Undo.AddComponent <CinemachineCollider>(vcam.gameObject);
                collider.m_AvoidObstacles = false;
                Undo.RecordObject(collider, "create ClearShot child");
                vcam.transform.SetSiblingIndex(index);
            };
            mChildList.onRemoveCallback = (UnityEditorInternal.ReorderableList l) =>
            {
                Object o = l.serializedProperty.GetArrayElementAtIndex(
                    l.index).objectReferenceValue;
                CinemachineVirtualCameraBase vcam = (o != null)
                        ? (o as CinemachineVirtualCameraBase) : null;
                if (vcam != null)
                {
                    Undo.DestroyObjectImmediate(vcam.gameObject);
                }
            };
        }
예제 #3
0
    public void DestroyDevicePrefab(string prefabName)
    {
#if UNITY_EDITOR
        if (!AvatarCheck())
        {
            return;
        }
        Transform target = null;
        switch (prefabName)
        {
        case "Vest":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_Vest_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_Vest_Hidden");
            }
            break;

        case "LeftArm":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_LeftArm_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_LeftArm_Hidden");
            }
            break;

        case "RightArm":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_RightArm_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_RightArm_Hidden");
            }
            break;

        case "Head":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_Head_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_Head_Hidden");
            }
            break;

        case "LeftHand":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_LeftHand_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_LeftHand_Hidden");
            }
            break;

        case "RightHand":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_RightHand_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_RightHand_Hidden");
            }
            break;

        case "LeftFoot":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_LeftFoot_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_LeftFoot_Hidden");
            }
            break;

        case "RightFoot":
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_RightFoot_Visualized");
            }
            if (target == null)
            {
                target = FindDeviceObject("BhapticsVRC_RightFoot_Hidden");
            }
            break;
        }
        if (target != null)
        {
            Undo.DestroyObjectImmediate(target.gameObject);
        }

        return;
#endif
    }
예제 #4
0
        void DrawSequenceView(FungusScript fungusScript)
        {
            GUILayout.Space(5);

            fungusScript.commandScrollPos = GUILayout.BeginScrollView(fungusScript.commandScrollPos);

            EditorGUILayout.BeginVertical();

            GUILayout.Box("Sequence", GUILayout.ExpandWidth(true));

            GUILayout.BeginHorizontal();

            if (fungusScript.selectedSequence == null)
            {
                GUILayout.FlexibleSpace();
            }

            if (GUILayout.Button(fungusScript.selectedSequence == null ? "Create Sequence" : "Create",
                                 fungusScript.selectedSequence == null ?  EditorStyles.miniButton : EditorStyles.miniButtonLeft))
            {
                Sequence newSequence = fungusScript.CreateSequence(fungusScript.scriptScrollPos);
                Undo.RegisterCreatedObjectUndo(newSequence, "New Sequence");
                fungusScript.selectedSequence = newSequence;
                fungusScript.selectedCommand  = null;
            }

            if (fungusScript.selectedSequence == null)
            {
                GUILayout.FlexibleSpace();
            }

            if (fungusScript.selectedSequence != null)
            {
                if (GUILayout.Button("Delete", EditorStyles.miniButtonMid))
                {
                    Undo.DestroyObjectImmediate(fungusScript.selectedSequence.gameObject);
                    fungusScript.selectedSequence = null;
                    fungusScript.selectedCommand  = null;
                }
                if (GUILayout.Button("Duplicate", EditorStyles.miniButtonRight))
                {
                    GameObject copy = GameObject.Instantiate(fungusScript.selectedSequence.gameObject) as GameObject;
                    copy.transform.parent    = fungusScript.transform;
                    copy.transform.hideFlags = HideFlags.HideInHierarchy;
                    copy.name = fungusScript.selectedSequence.name;

                    Sequence sequenceCopy = copy.GetComponent <Sequence>();
                    sequenceCopy.nodeRect.x += sequenceCopy.nodeRect.width + 10;

                    Undo.RegisterCreatedObjectUndo(copy, "Duplicate Sequence");
                    fungusScript.selectedSequence = sequenceCopy;
                    fungusScript.selectedCommand  = null;
                }
            }

            GUILayout.EndHorizontal();

            if (fungusScript.selectedSequence != null)
            {
                EditorGUILayout.Separator();

                SequenceEditor sequenceEditor = Editor.CreateEditor(fungusScript.selectedSequence) as SequenceEditor;
                sequenceEditor.DrawSequenceGUI(fungusScript);
                DestroyImmediate(sequenceEditor);

                GUILayout.FlexibleSpace();
            }

            EditorGUILayout.EndVertical();

            GUILayout.EndScrollView();
        }
예제 #5
0
 public void UndoRemoveAnimation(TweenAnimation animation)
 {
     Undo.RecordObject(this, "RemoveAnimation");
     _animations.Remove(animation);
     Undo.DestroyObjectImmediate(animation);
 }
        protected override void OnEnable()
        {
            base.OnEnable();
            Undo.undoRedoPerformed += ResetTargetOnUndo;
            m_PipelineSet.Initialize(
                // GetComponent
                (stage, result) =>
            {
                int numNullComponents = 0;
                foreach (var obj in targets)
                {
                    var vcam = obj as CinemachineVirtualCamera;
                    if (vcam != null)
                    {
                        var c = vcam.GetCinemachineComponent(stage);
                        if (c != null)
                        {
                            result.Add(c);
                        }
                        else
                        {
                            ++numNullComponents;
                        }
                    }
                }
                return(numNullComponents);
            },
                // SetComponent
                (stage, type) =>
            {
                Undo.SetCurrentGroupName("Cinemachine pipeline change");
                foreach (var obj in targets)
                {
                    var vcam        = obj as CinemachineVirtualCamera;
                    Transform owner = vcam == null ? null : vcam.GetComponentOwner();
                    if (owner == null)
                    {
                        continue;     // maybe it's a prefab
                    }
                    var c = vcam.GetCinemachineComponent(stage);
                    if (c != null && c.GetType() == type)
                    {
                        continue;
                    }
                    if (c != null)
                    {
                        Undo.DestroyObjectImmediate(c);
                        vcam.InvalidateComponentPipeline();
                    }
                    if (type != null)
                    {
                        Undo.AddComponent(owner.gameObject, type);
                        vcam.InvalidateComponentPipeline();
                    }
                }
            });

            // We only look at the first target here, on purpose
            if (Target != null && Target.m_LockStageInInspector != null)
            {
                foreach (var s in Target.m_LockStageInInspector)
                {
                    m_PipelineSet.SetStageIsLocked(s);
                }
            }
        }
예제 #7
0
		public void  OnSceneGUI ()
		{	
			if (script == null) script = (MapMagic)target;
			MapMagic.instance = script;
			if (!script.enabled) return;
			script.terrains.CheckEmpty();
			

			#region Drawing Selection

			//drawing frames
			if (Event.current.type == EventType.Repaint)
			foreach(Coord coord in MapMagic.instance.terrains.Coords())
			{
				Handles.color = nailColor*0.8f;
				if (MapMagic.instance.terrains[coord].locked) Handles.color = lockColor*0.8f;
				DrawSelectionFrame(coord, 5f);
			}

			#endregion
		

			#region Selecting terrains
			if (selectionMode==SelectionMode.nailing || selectionMode==SelectionMode.locking)
			{
				//disabling selection
				HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

				//finding aiming ray
				/*Vector2 mousePos = Event.current.mousePosition;
				mousePos.y = Screen.height - mousePos.y - 40;
				Camera cam = UnityEditor.SceneView.lastActiveSceneView.camera;
				if (cam==null) return;
				Ray aimRay = cam.ScreenPointToRay(mousePos);*/
				SceneView sceneview = UnityEditor.SceneView.lastActiveSceneView;
				if (sceneview==null || sceneview.camera==null) return;
				Vector2 mousePos = Event.current.mousePosition;
				mousePos = new Vector2(mousePos.x/sceneview.camera.pixelWidth, 1-mousePos.y/sceneview.camera.pixelHeight);
				#if UNITY_5_4_OR_NEWER 
				mousePos *= EditorGUIUtility.pixelsPerPoint;
				#endif
				Ray aimRay = sceneview.camera.ViewportPointToRay(mousePos);

				//aiming terrain or empty place
				Vector3 aimPos = Vector3.zero;
				RaycastHit hit;
				if (Physics.Raycast(aimRay, out hit, Mathf.Infinity)) aimPos = hit.point;
				else
				{
					aimRay.direction = aimRay.direction.normalized;
					float aimDist = aimRay.origin.y / (-aimRay.direction.y);
					aimPos = aimRay.origin + aimRay.direction*aimDist;
				}
				aimPos -= MapMagic.instance.transform.position;

				Coord aimCoord = aimPos.FloorToCoord(MapMagic.instance.terrainSize);

				if (selectionMode == SelectionMode.nailing && !Event.current.alt)
				{
					//drawing selection frame
					Handles.color = nailColor;
					DrawSelectionFrame(aimCoord, width:5f);

					//selecting / unselecting
					if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
					{
						if (MapMagic.instance.terrains[aimCoord]==null) //if obj not exists - nail
						{
							Undo.RegisterFullObjectHierarchyUndo(MapMagic.instance, "MapMagic Pin Terrain");
							MapMagic.instance.terrains.Nail(aimCoord); 
							//MapMagic.instance.terrains.maxCount++;
						}
						else 
						{
							Undo.DestroyObjectImmediate(MapMagic.instance.terrains[aimCoord].terrain.gameObject);
							Undo.RecordObject(MapMagic.instance, "MapMagic Unpin Terrain");
							MapMagic.instance.setDirty = !MapMagic.instance.setDirty;

							MapMagic.instance.terrains.Unnail(aimCoord); 
							//MapMagic.instance.terrains.maxCount--;
						}
						//if (MapMagic.instance.terrains.maxCount < MapMagic.instance.terrains.nailedHashes.Count+4) MapMagic.instance.terrains.maxCount = MapMagic.instance.terrains.nailedHashes.Count+4;
						//EditorUtility.SetDirty(MapMagic.instance); //already done via undo
					}
				}

				if (selectionMode == SelectionMode.locking  && !Event.current.alt)
				{
					Chunk aimedTerrain = MapMagic.instance.terrains[aimCoord];
					if (aimedTerrain != null)
					{
						//drawing selection frame
						Handles.color = lockColor;
						DrawSelectionFrame(aimCoord, width:5f);

						//selecting / unselecting
						if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
						{
							Undo.RecordObject(MapMagic.instance, "MapMagic Lock Terrain");
							MapMagic.instance.setDirty = !MapMagic.instance.setDirty;

							aimedTerrain.locked = !aimedTerrain.locked;
							//EditorUtility.SetDirty(MapMagic.instance); //already done via undo
						}
					}
				}
				
				//redrawing scene by moving temp object
				if (script.sceneRedrawObject==null) { script.sceneRedrawObject = new GameObject(); script.sceneRedrawObject.hideFlags = HideFlags.HideInHierarchy; }
				script.sceneRedrawObject.transform.position = aimPos;
			}
			#endregion
		}
예제 #8
0
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        TxEditor.LookLikeControls();

        bool isPlaying = Application.isPlaying;

        TxTrussDesigner trussDesigner = m_targets[0].GetComponent <TxTrussDesigner>();

        GUI.enabled = (trussDesigner == null && !Application.isPlaying) && !isPlaying;
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PropertyField(truss);
        GUI.enabled = (truss.objectReferenceValue != null && !Application.isPlaying);
        if (GUILayout.Button("Edit", (trussDesigner != null) ? TxEditor.MiniPressedStyle() : TxEditor.MiniUnpressedStyle(), GUILayout.MaxWidth(40)))
        {
            if (trussDesigner)
            {
                EditorApplication.delayCall += () => Undo.DestroyObjectImmediate(trussDesigner);
            }
            else
            {
                Undo.AddComponent <TxTrussDesigner>(m_targets[0].gameObject);
            }
        }
        EditorGUILayout.EndHorizontal();

        GUI.enabled = true;
        EditorGUILayout.PropertyField(massScale);
        if (truss.objectReferenceValue == null || truss.hasMultipleDifferentValues || massScale.hasMultipleDifferentValues)
        {
            GUI.enabled = false;
            EditorGUILayout.TextField("Scaled Mass", "-");
        }
        else
        {
            TxTruss trussAsset = truss.objectReferenceValue as TxTruss;
            if (trussAsset != null)
            {
                float scaledMass = 0;
                foreach (var m in trussAsset.nodeMass)
                {
                    scaledMass += m;
                }
                GUI.enabled = false;
                EditorGUILayout.FloatField("Scaled Mass", scaledMass * massScale.floatValue);
            }
        }

        GUI.enabled = true && !isPlaying;
        EditorGUILayout.PropertyField(collision);

        EditorGUI.indentLevel++;
        GUI.enabled = collision.boolValue && !isPlaying;
        EditorGUILayout.PropertyField(margin);
        EditorGUILayout.PropertyField(matters, true);
        EditorGUI.indentLevel--;

        BodyGroupUI();

        GUI.enabled = true && !isPlaying;
        EditorGUILayout.PropertyField(skinning);

        GUI.enabled = true && !isPlaying;
        SpawnEnabledUI();
        EditorGUI.indentLevel++;
        EditorGUILayout.PropertyField(spawnActive);
        EditorGUI.indentLevel--;
        GUI.enabled = true;
        EditorGUILayout.PropertyField(deactivation);
        EditorGUI.indentLevel++;
        GUI.enabled = deactivation.boolValue;
        EditorGUILayout.PropertyField(deactivationSpeed, new GUIContent("Speed"));
        EditorGUILayout.PropertyField(deactivationTime, new GUIContent("Time"));
        EditorGUI.indentLevel--;

        GUI.enabled = true;
        EditorGUILayout.PropertyField(filling);
        EditorGUI.indentLevel++;
        GUI.enabled = filling.boolValue;
        EditorGUILayout.PropertyField(internalPressure);
        EditorGUILayout.PropertyField(adiabaticIndex);
        EditorGUI.indentLevel--;

        GUI.enabled = true;
        EditorGUILayout.PropertyField(fastRotation);

        if (GUI.changed)
        {
            serializedObject.ApplyModifiedProperties();
        }
    }
예제 #9
0
        public void ConvertToLayoutPanel()
        {
            if (name.Contains(LayoutPanel.spacerName))
                name = "Item " + LayoutExt.RandomString(4);
            AddBordersOnly();
            AddTop();
            HandleContent();
            HandleThisObject();
            HandleTopLabel();
            Fold(GetComponent<RectTransform>());
            TryToGetReferences();

            // if (panel.GetComponentInParent<LayoutColumn>() == null)
            // {
            //     Debug.Log("Set freemode");
            //     panel.freeMode = true;
            // }

#if UNITY_EDITOR
            if (Selection.activeGameObject == gameObject)
                EditorGUIUtility.PingObject(content);
            //Selection.activeObject = content;
            if (removeMeWhenDone) EditorApplication.delayCall += () => EditorApplication.delayCall += () => { if (this != null) Undo.DestroyObjectImmediate(this); };
#endif
        }
예제 #10
0
        protected override void AddComponentMenuButton()
        {
            var componentTabSelection = MarsInspectorSharedSettings.Instance.ComponentTabSelection;

            // Skip this button in the case of Forces, because they have their more complex button already and this button is redundant.
            if (componentTabSelection == k_ForcesTab)
            {
                return;
            }

            var tabIsAllOrSettings = componentTabSelection == k_AllTabs || componentTabSelection == k_SettingsTab;

            var addComponentText = "Add MARS Component...";

            if (!tabIsAllOrSettings)
            {
                switch (componentTabSelection)
                {
                case k_ConditionsTab:
                    addComponentText = "Add Condition...";
                    break;

                case k_ActionsTab:
                    addComponentText = "Add Action...";
                    break;

                case k_ForcesTab:
                    addComponentText = "Add Force...";
                    break;
                }
            }

            if (GUILayout.Button(addComponentText, EditorStyles.miniButton))
            {
                var menu    = new GenericMenu();
                var isGroup = (m_BaseEditor.target is ProxyGroup);

                foreach (var kvp in k_ComponentTypes)
                {
                    var type = kvp.Key;

                    if (isGroup && !(type.IsSubclassOf(typeof(Relation))))
                    {
                        continue;
                    }

                    if (!CanDrawSelectedOption(null, type, true))
                    {
                        continue;
                    }

                    // Check if this component cannot be added because another of its exclusive siblings is added
                    m_ConflictingBehaviors.Clear();
                    var componentClash = HasComponentClash(type, m_ComponentList, false, m_ConflictingBehaviors);

                    if (!componentClash)
                    {
                        componentClash = HasRequirementClash(type, m_ComponentList);
                    }
                    else if (m_ConflictingBehaviors.Count > 0)
                    {
                        m_ConflictingBehaviors.RemoveAll(alternate => HasRequirementClash(alternate.GetType(), m_ComponentList));
                    }

                    var menuItem = EditorGUIUtils.GetContent(kvp.Value.menuItem);

                    if (!tabIsAllOrSettings)
                    {
                        var modifiedMenuItem = new GUIContent(menuItem);
                        var text             = modifiedMenuItem.text;
                        // If we're in a filtered tab, don't show the first-layer menu (Conditions, Actions, Forces),
                        // because it would be redundant with the tab itself.
                        modifiedMenuItem.text = text.Substring(text.IndexOf("/", StringComparison.Ordinal) + 1);
                        menuItem = modifiedMenuItem;
                    }

                    if (!componentClash)
                    {
                        menu.AddItem(menuItem, false, () => AddComponent(type));
                    }
                    else if (m_ConflictingBehaviors.Count > 0)
                    {
                        var conflictingComponent = m_ConflictingBehaviors[0];

                        var conflictingTypeName = conflictingComponent.GetType().Name;
                        if (k_ComponentTypes.ContainsKey(conflictingComponent.GetType()))
                        {
                            conflictingTypeName = k_ComponentTypes[conflictingComponent.GetType()].menuItem;
                            if (conflictingTypeName.Contains("/"))
                            {
                                conflictingTypeName = conflictingTypeName.Substring(conflictingTypeName.IndexOf("/", StringComparison.Ordinal) + 1);
                            }
                        }

                        var insertText   = $"Replace/{conflictingTypeName} with";
                        var menuItemText = menuItem.text;
                        if (menuItemText.Contains("/"))
                        {
                            var lastIndex = menuItemText.IndexOf("/", StringComparison.Ordinal);
                            menuItemText = menuItemText.Insert(lastIndex, "/" + insertText);
                        }
                        else
                        {
                            menuItemText = insertText + "/" + menuItemText;
                        }

                        menu.AddItem(new GUIContent(menuItemText), false, () =>
                        {
                            Undo.DestroyObjectImmediate(conflictingComponent);
                            AddComponent(type);
                        });
                    }
                }

                menu.ShowAsContext();
            }
        }
예제 #11
0
        private void DrawPathOptions()
        {
            editOption = (PathModifierOption)EditorGUILayout.EnumPopup(editOption);

            switch (editOption)
            {
            case PathModifierOption.PlaceToGround:
                foreach (BezierPoint bp in script.bPoints)
                {
                    //define ray to cast downwards waypoint position
                    Ray ray = new Ray(bp.wp.position + new Vector3(0, 2f, 0), -Vector3.up);
                    Undo.RecordObject(bp.wp, "Place To Ground");

                    RaycastHit hit;
                    //cast ray against ground, if it hit:
                    if (Physics.Raycast(ray, out hit, 100))
                    {
                        //position waypoint to hit point
                        bp.wp.position = hit.point;
                    }

                    //also try to raycast against 2D colliders
                    RaycastHit2D hit2D = Physics2D.Raycast(ray.origin, -Vector2.up, 100);
                    if (hit2D)
                    {
                        bp.wp.position = new Vector3(hit2D.point.x, hit2D.point.y, bp.wp.position.z);
                    }
                }
                break;

            case PathModifierOption.InvertDirection:
                //does not do anything actually
                Undo.RecordObject(script, "Invert Direction");

                //to reverse the whole path we need to know where the waypoints were before
                //for this purpose a new copy must be created
                List <List <Vector3> > waypointCopy = new List <List <Vector3> >();
                for (int i = 0; i < script.bPoints.Count; i++)
                {
                    BezierPoint curPoint = script.bPoints[i];
                    waypointCopy.Add(new List <Vector3>()
                    {
                        curPoint.wp.position, curPoint.cp[0].position, curPoint.cp[1].position
                    });
                }

                //reverse order based on the old list
                for (int i = 0; i < script.bPoints.Count; i++)
                {
                    BezierPoint curPoint = script.bPoints[i];
                    curPoint.wp.position    = waypointCopy[waypointCopy.Count - 1 - i][0];
                    curPoint.cp[0].position = waypointCopy[waypointCopy.Count - 1 - i][2];
                    curPoint.cp[1].position = waypointCopy[waypointCopy.Count - 1 - i][1];
                }

                break;

            case PathModifierOption.RotateWaypointsToPath:
                Undo.RecordObject(script, "Rotate Waypoints");

                //orient waypoints to the path in forward direction
                for (int i = 0; i < script.bPoints.Count; i++)
                {
                    //save child rotations before applying waypoint rotation
                    Vector3[] globalPos = new Vector3[script.bPoints[i].wp.childCount];
                    for (int j = 0; j < globalPos.Length; j++)
                    {
                        globalPos[j] = script.bPoints[i].wp.GetChild(j).position;
                    }

                    if (i == script.bPoints.Count - 1)
                    {
                        script.bPoints[i].wp.rotation = script.bPoints[i - 1].wp.rotation;
                    }
                    else
                    {
                        script.bPoints[i].wp.LookAt(script.bPoints[i + 1].wp);
                    }

                    //restore previous location after rotation
                    for (int j = 0; j < globalPos.Length; j++)
                    {
                        script.bPoints[i].wp.GetChild(j).position = globalPos[j];
                    }
                }
                break;

            case PathModifierOption.RenameWaypoints:
                //disabled because of a Unity bug that crashes the editor
                //this is taken directly from the docs, thank you Unity.
                //http://docs.unity3d.com/ScriptReference/Undo.RegisterCompleteObjectUndo.html
                //Undo.RegisterCompleteObjectUndo(waypoints[0].gameObject, "Rename Waypoints");
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Skip Custom Names?");
                script.skipCustomNames = EditorGUILayout.Toggle(script.skipCustomNames, GUILayout.Width(20));
                EditorGUILayout.EndHorizontal();

                if (!GUILayout.Button("Rename Now"))
                {
                    return;
                }

                RenameWaypoints(script.skipCustomNames);
                break;

            case PathModifierOption.UpdateFromChildren:
                Undo.RecordObject(script, "Update Path From Children");
                script.Create();
                SceneView.RepaintAll();
                break;

            case PathModifierOption.ReplaceWaypointObject:
                //draw object field for new waypoint object
                script.replaceObject = (GameObject)EditorGUILayout.ObjectField("Replace Object", script.replaceObject, typeof(GameObject), true);

                //replace all waypoints with the prefab
                if (!GUILayout.Button("Replace Now"))
                {
                    return;
                }
                else if (script.replaceObject == null)
                {
                    Debug.LogWarning("No replace object set. Cancelling.");
                    return;
                }

                //Undo.RecordObject(script, "Replace Object");
                Undo.RegisterFullObjectHierarchyUndo(script.transform, "Replace Object");

                //old waypoints to remove after replace
                List <GameObject> toRemove = new List <GameObject>();
                //loop through waypoint list
                for (int i = 0; i < script.bPoints.Count; i++)
                {
                    //get current bezier point at index position
                    BezierPoint point = script.bPoints[i];
                    Transform   curWP = point.wp;
                    //instantiate new waypoint at old position
                    Transform newCur = ((GameObject)Instantiate(script.replaceObject, curWP.position, Quaternion.identity)).transform;
                    //Undo.RegisterCreatedObjectUndo(newCur.gameObject, "Replace Object");

                    //parent control points to the new bezier point
                    Undo.SetTransformParent(point.cp[0], newCur, "Replace Object");
                    Undo.SetTransformParent(point.cp[1], newCur, "Replace Object");
                    //parent new waypoint to this path
                    newCur.parent = point.wp.parent;

                    //replace old waypoint at index
                    script.bPoints[i].wp = newCur;
                    //indicate to remove old waypoint
                    toRemove.Add(curWP.gameObject);
                }

                //destroy old waypoint object
                for (int i = 0; i < toRemove.Count; i++)
                {
                    Undo.DestroyObjectImmediate(toRemove[i]);
                }

                break;
            }

            editOption = PathModifierOption.SelectModifier;
        }
예제 #12
0
    // Source: http://projectperko.blogspot.com/2016/08/multi-material-mesh-merge-snippet.html, with changes
    public static void ConvertToMesh(GameObject gameObject, string name)
    {
        List <MeshFilter> meshFilters = new List <MeshFilter>(gameObject.GetComponentsInChildren <MeshFilter>());
        List <Material>   materials   = new List <Material>();

        MeshRenderer[] meshRenderers = gameObject.GetComponentsInChildren <MeshRenderer>();

        // Support objects with more materials than meshes
        for (int i = 0; i < meshFilters.Count; i++)
        {
            if (meshFilters[i].sharedMesh != null)
            {
                if (meshFilters[i].GetComponent <MeshRenderer>().sharedMaterials.Length > meshFilters[i].sharedMesh.subMeshCount)
                {
                    meshFilters[i].sharedMesh.subMeshCount += 1;
                    meshFilters[i].sharedMesh.SetTriangles(meshFilters[i].sharedMesh.triangles, 1);
                }
            }
            else
            {
                meshFilters.RemoveAt(i);
            }
        }

        foreach (MeshRenderer meshRenderer in meshRenderers)
        {
            Material[] localMaterials = meshRenderer.sharedMaterials;

            foreach (Material localMaterial in localMaterials)
            {
                if (!materials.Contains(localMaterial))
                {
                    materials.Add(localMaterial);
                }
            }
        }

        List <Mesh> subMeshes = new List <Mesh>();

        foreach (Material material in materials)
        {
            List <CombineInstance> combineInstances = new List <CombineInstance>();
            foreach (MeshFilter meshFilter in meshFilters)
            {
                MeshRenderer meshRenderer   = meshFilter.GetComponent <MeshRenderer>();
                Material[]   localMaterials = meshRenderer.sharedMaterials;

                for (int materialIndex = 0; materialIndex < localMaterials.Length; materialIndex++)
                {
                    if (localMaterials[materialIndex] != material)
                    {
                        continue;
                    }

                    CombineInstance combineInstance = new CombineInstance();
                    combineInstance.mesh         = meshFilter.sharedMesh;
                    combineInstance.subMeshIndex = materialIndex;
                    Matrix4x4 matrix = Matrix4x4.identity;
                    matrix.SetTRS(meshFilter.transform.position, meshFilter.transform.rotation, meshFilter.transform.lossyScale);
                    combineInstance.transform = matrix;
                    combineInstances.Add(combineInstance);
                }
            }

            Mesh mesh = new Mesh();
            mesh.CombineMeshes(combineInstances.ToArray(), true);
            subMeshes.Add(mesh);
        }

        List <CombineInstance> finalCombiners = new List <CombineInstance>();

        foreach (Mesh mesh in subMeshes)
        {
            CombineInstance combineInstance = new CombineInstance();
            combineInstance.mesh         = mesh;
            combineInstance.subMeshIndex = 0;
            combineInstance.transform    = Matrix4x4.identity;
            finalCombiners.Add(combineInstance);
        }

        Mesh finalMesh = new Mesh();

        finalMesh.CombineMeshes(finalCombiners.ToArray(), false);

        GameObject newMesh = new GameObject(name);

        Undo.RegisterCreatedObjectUndo(newMesh, "Create Combined Mesh");
        newMesh.AddComponent <MeshFilter>();
        newMesh.AddComponent <MeshRenderer>();
        newMesh.AddComponent <MeshCollider>();
        newMesh.GetComponent <MeshFilter>().sharedMesh        = finalMesh;
        newMesh.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
        newMesh.GetComponent <MeshCollider>().sharedMesh      = finalMesh;
        Selection.activeGameObject = newMesh;
        Undo.DestroyObjectImmediate(gameObject.gameObject);
    }
예제 #13
0
    public override void OnInspectorGUI()
    {
        if (prefabCreator.spacing == -1)
        {
            if (prefabCreator.prefab == null)
            {
                prefabCreator.prefab = (GameObject)prefabCreator.settings.FindProperty("defaultPrefabLinePrefab").objectReferenceValue;
            }

            prefabCreator.spacing = prefabCreator.prefab.GetComponent <MeshFilter>().sharedMesh.bounds.extents.x * 2 * prefabCreator.xScale;
        }

        EditorGUI.BeginChangeCheck();
        prefabCreator.pointCalculationDivisions = Mathf.Clamp(EditorGUILayout.FloatField("Point Calculation Divisions", prefabCreator.pointCalculationDivisions), 1, 1000);
        prefabCreator.rotateAlongCurve          = EditorGUILayout.Toggle("Rotate Alongst Curve", prefabCreator.rotateAlongCurve);
        if (prefabCreator.rotateAlongCurve == true)
        {
            prefabCreator.rotationDirection = (PrefabLineCreator.RotationDirection)EditorGUILayout.EnumPopup("Rotation Direction", prefabCreator.rotationDirection);

            if (prefabCreator.fillGap == false)
            {
                prefabCreator.yRotationRandomization = Mathf.Clamp(EditorGUILayout.FloatField("Y Rotation Randomization", prefabCreator.yRotationRandomization), 0, 360);
            }
            else
            {
                prefabCreator.yRotationRandomization = 0;
            }

            prefabCreator.bendObjects = GUILayout.Toggle(prefabCreator.bendObjects, "Bend Objects");
        }
        else if (prefabCreator.bendObjects == true)
        {
            Debug.Log("Rotate alongst curve has to be true to be able to use bend objects");
            prefabCreator.bendObjects = false;
        }

        if (prefabCreator.rotateAlongCurve == true)
        {
            prefabCreator.fillGap = GUILayout.Toggle(prefabCreator.fillGap, "Fill Gap");
        }
        else if (prefabCreator.fillGap == true)
        {
            Debug.Log("Rotate alongst curve has to be true to be able to use fill gap");
            prefabCreator.fillGap = false;
        }

        if (prefabCreator.fillGap == false && prefabCreator.bendObjects == false)
        {
            prefabCreator.spacing = Mathf.Max(0.1f, EditorGUILayout.FloatField("Spacing", prefabCreator.spacing));

            if (GUILayout.Button("Calculate Spacing (X)") == true)
            {
                prefabCreator.spacing = prefabCreator.prefab.GetComponent <MeshFilter>().sharedMesh.bounds.extents.x * 2 * prefabCreator.xScale;
            }

            if (GUILayout.Button("Calculate Spacing (Z)") == true)
            {
                if (prefabCreator.prefab != null)
                {
                    prefabCreator.spacing = prefabCreator.prefab.GetComponent <MeshFilter>().sharedMesh.bounds.extents.z * 2 * prefabCreator.zScale;
                }
            }
        }

        prefabCreator.yModification = (PrefabLineCreator.YModification)EditorGUILayout.EnumPopup("Vertex Y Modification", prefabCreator.yModification);

        if (prefabCreator.yModification == PrefabLineCreator.YModification.matchTerrain)
        {
            prefabCreator.terrainCheckHeight = Mathf.Max(0, EditorGUILayout.FloatField("Check Terrain Height", prefabCreator.terrainCheckHeight));
        }

        GUIStyle guiStyle = new GUIStyle();

        guiStyle.fontStyle = FontStyle.Bold;

        GUILayout.Space(20);
        GUILayout.Label("Prefabs", guiStyle);
        prefabCreator.prefab      = (GameObject)EditorGUILayout.ObjectField("Prefab", prefabCreator.prefab, typeof(GameObject), false);
        prefabCreator.startPrefab = (GameObject)EditorGUILayout.ObjectField("Start Prefab", prefabCreator.startPrefab, typeof(GameObject), false);
        prefabCreator.endPrefab   = (GameObject)EditorGUILayout.ObjectField("End Prefab", prefabCreator.endPrefab, typeof(GameObject), false);

        GUILayout.Space(20);
        GUILayout.Label("Scaling", guiStyle);
        prefabCreator.xScale = Mathf.Clamp(EditorGUILayout.FloatField("Prefab X Scale", prefabCreator.xScale), 0.1f, 10);
        prefabCreator.yScale = Mathf.Clamp(EditorGUILayout.FloatField("Prefab Y Scale", prefabCreator.yScale), 0.1f, 10);
        prefabCreator.zScale = Mathf.Clamp(EditorGUILayout.FloatField("Prefab Z Scale", prefabCreator.zScale), 0.1f, 10);

        if (EditorGUI.EndChangeCheck() == true)
        {
            if (prefabCreator.prefab == null)
            {
                prefabCreator.prefab = (GameObject)prefabCreator.settings.FindProperty("defaultPrefabLinePrefab").objectReferenceValue;
            }
            else if (prefabCreator.prefab.GetComponent <MeshFilter>() == null)
            {
                prefabCreator.prefab = (GameObject)prefabCreator.settings.FindProperty("defaultPrefabLinePrefab").objectReferenceValue;
                Debug.Log("Selected prefab must have a mesh filter attached. Prefab has been changed to the concrete barrier");
                return;
            }

            if (prefabCreator.fillGap == true || prefabCreator.bendObjects == true)
            {
                prefabCreator.spacing = prefabCreator.prefab.GetComponent <MeshFilter>().sharedMesh.bounds.extents.x * 2 * prefabCreator.xScale;
            }

            prefabCreator.PlacePrefabs();
        }

        GUILayout.Space(20);

        if (GUILayout.Button("Reset"))
        {
            for (int i = 1; i >= 0; i--)
            {
                for (int j = prefabCreator.transform.GetChild(i).childCount - 1; j >= 0; j--)
                {
                    Undo.DestroyObjectImmediate(prefabCreator.transform.GetChild(i).GetChild(j).gameObject);
                }
            }
        }

        if (GUILayout.Button("Place Prefabs"))
        {
            prefabCreator.PlacePrefabs();
        }
    }
예제 #14
0
        /// <summary>
        /// Custom inspector override for buttons.
        /// </summary>
        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();
            EditorGUILayout.Space();

            //display current count of placed vertices in the active submesh
            EditorGUILayout.LabelField("Current Vertices: " + script.current.Count);

            //enter placement mode
            if (!placing && GUILayout.Button("Edit Mode: Off"))
            {
                Undo.RegisterCompleteObjectUndo(script, "Edit On");

                //if possible, create new submesh
                if (CheckSubMesh())
                {
                    GameObject newObj = script.CreateSubMesh();
                    Undo.RegisterCreatedObjectUndo(newObj, "Edit On");
                }

                //clear handle selections
                selected.Clear();
                placing = true;
            }

            GUI.color = Color.yellow;

            //leave placement mode and try to combine submeshes
            if (placing && GUILayout.Button("Edit Mode: On"))
            {
                Undo.RegisterCompleteObjectUndo(script, "Edit Off");

                //if possible, combine submeshes
                if (CheckCombine())
                {
                    //get all mesh filters
                    MeshFilter[] meshFilters = script.GetComponentsInChildren <MeshFilter>();
                    Undo.RecordObject(meshFilters[0], "Edit Off");

                    //let the script combine them
                    script.Combine();

                    for (int i = 1; i < meshFilters.Length; i++)
                    {
                        Undo.DestroyObjectImmediate(meshFilters[i].gameObject);
                    }
                }

                placing = false;
            }

            GUI.color = Color.white;

            //export mesh to asset and prefab
            if (GUILayout.Button("Save as Prefab"))
            {
                //get gameobject and its mesh filter
                GameObject gObj = script.gameObject;
                Mesh       mesh = gObj.GetComponent <MeshFilter>().sharedMesh;

                if (!mesh)
                {
                    Debug.LogWarning("Could not save as prefab, asset does not have a Mesh.");
                    return;
                }

                if (AssetDatabase.Contains(mesh))
                {
                    Debug.Log("Mesh asset already exists. Cancelling.");
                    return;
                }

                //get the current unix timestamp for a unique naming scheme
                var    epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
                string timestamp  = (System.DateTime.UtcNow - epochStart).TotalSeconds.ToString("F0");
                string assetName  = "NavMesh_";

                //check that the folder does exist
                string dir = Path.GetDirectoryName(assetPath);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                    AssetDatabase.ImportAsset(dir);
                }

                //create the mesh asset at the path specified, with unique name
                AssetDatabase.CreateAsset(mesh, assetPath + assetName + timestamp + ".asset");
                AssetDatabase.SaveAssets();

                //create the prefab of this gameobject at the path specified, with the same name
                PrefabUtility.CreatePrefab(assetPath + assetName + timestamp + ".prefab", gObj,
                                           ReplacePrefabOptions.ConnectToPrefab);
                //rename instance to prefab name
                gObj.name = assetName + timestamp;
            }

            if (placing)
            {
                EditorGUILayout.Separator();
                EditorGUILayout.LabelField("Hint:", EditorStyles.boldLabel);
                EditorGUILayout.TextArea("Click on colliders to place vertices.\n" +
                                         "CTRL + click to start a new submesh.");
            }
        }
    public void Draw(State state)
    {
        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Add"))
        {
            Undo.AddComponent <GroupConnection>(state.gameObject);
        }
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.Space();
        groupsScroll = EditorGUILayout.BeginScrollView(groupsScroll);
        var groupConnections = state.GetComponents <GroupConnection>();

        foreach (var groupConnection in groupConnections)
        {
            var groupConnectionTitle = GetTitleStringOf(groupConnection.title);
            GUILayout.Label(groupConnectionTitle, EditorStyles.boldLabel);

            EditorGUI.indentLevel++;

            Undo.RecordObject(groupConnection, "Edit group connection title");
            groupConnection.title = EditorGUILayout.TextField("Title:", groupConnection.title);

            var buttonStyle = Styles.ToggleButtonStyleNormal;
            if (StateItemPlaceEditor.EditableItem == groupConnection)
            {
                buttonStyle = Styles.ToggleButtonStyleToggled;
            }

            if (GUI.Button(EditorGUI.IndentedRect(EditorGUILayout.GetControlRect()), "edit", buttonStyle))
            {
                if (StateItemPlaceEditor.EditableItem == groupConnection)
                {
                    StateItemPlaceEditor.CleadEditing();
                }
                else
                {
                    StateItemPlaceEditor.EnableEditing(state, groupConnection, Color.green);
                }
            }

            EditorGUILayout.Space();


            var connections = state.GetComponents <Connection>();

            if (connections.Length > 0)
            {
                if (GUI.Button(EditorGUI.IndentedRect(EditorGUILayout.GetControlRect()), $"Add connection"))
                {
                    GenericMenu menu = new GenericMenu();

                    foreach (var connection in connections)
                    {
                        menu.AddItem(new GUIContent(connection.Destination.title), false, o =>
                        {
                            var selectedConnection = o as Connection;
                            Undo.RecordObject(groupConnection, "Add state reference");
                            groupConnection.states.Add(selectedConnection.Destination);

                            Undo.DestroyObjectImmediate(selectedConnection);
                        }, connection);
                    }
                    menu.ShowAsContext();
                }
            }
            else
            {
                GUILayout.Label("No available connections to add");
            }
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("State references:");
            EditorGUI.indentLevel++;
            foreach (var stateReference in groupConnection.states)
            {
                EditorGUILayout.LabelField(stateReference.title);
                var line = EditorGUILayout.BeginHorizontal();

                GUILayout.Space(40);

                if (GUILayout.Button("Move to"))
                {
                    StateEditorWindow.FocusCamera(stateReference.gameObject);
                }

                if (GUILayout.Button("To simple connection"))
                {
                    Undo.RecordObject(groupConnection, "Delete state reference");
                    groupConnection.states.Remove(stateReference);
                    var addedConnection = Undo.AddComponent <Connection>(state.gameObject);
                    addedConnection.Destination = stateReference;
                    break;
                }

                if (GUILayout.Button("Delete", Styles.DeleteButtonStyle))
                {
                    Undo.RecordObject(groupConnection, "Delete state reference");
                    groupConnection.states.Remove(stateReference);
                    break;
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUI.indentLevel--;
            EditorGUI.indentLevel--;
        }
        EditorGUILayout.EndScrollView();
    }
예제 #16
0
        public void RemoveMe()
        {
#if UNITY_EDITOR
            Undo.DestroyObjectImmediate(this);
#endif
        }
예제 #17
0
 // Remove itself from the patch.
 public void RemoveFromPatch(Patch patch)
 {
     Undo.DestroyObjectImmediate(_instance.gameObject);
 }
예제 #18
0
  public static void ExplodeSketchByColor() {
    if (!EditorUtility.DisplayDialog ("Different Strokes", "Separate brush strokes of different colors into separate objects? \n* Note: This is an experimental feature!", "OK", "Cancel"))
      return;
    Undo.IncrementCurrentGroup();
    Undo.SetCurrentGroupName("Separate sketch by color");
    List<GameObject> newSelection = new List<GameObject>();
    bool cancel = false;

    var tri = new int[3] { 0, 0, 0 };

    foreach (var o in Selection.gameObjects) {
      if (cancel) break;
      var obj = GameObject.Instantiate(o, o.transform.position, o.transform.rotation) as GameObject;
      obj.name = o.name + " (Separated)";
      Undo.RegisterCreatedObjectUndo(obj, "Separate sketch by color");
      newSelection.Add(obj);
      int count = 0;

      foreach (var m in obj.GetComponentsInChildren<MeshFilter>()) {
        if (cancel) break;
        var mesh = m.sharedMesh;
        var meshColors = mesh.colors;

        // Keep a list of triangles for each color (as a vector) we find
        Dictionary<Vector3, List<int>> colors = new Dictionary<Vector3, List<int>>();

        var triangles = mesh.triangles;
        const int PROGRESS_FREQUENCY = 600;

        for (int i = 0; i < triangles.Length; i += 3) {
          if (++count > PROGRESS_FREQUENCY) {
            count = 0;
            cancel = EditorUtility.DisplayCancelableProgressBar("Separating sketch", "Processing " + mesh.name, (float)i / (float)triangles.Length);
            if (cancel) break;
          }

          tri[0] = triangles[i];
          tri[1] = triangles[i + 1];
          tri[2] = triangles[i + 2];

          // Get the triangle's average color
          var color = GetTriangleColorVec(meshColors, tri);

          // Add the triangle to the triangle-by-color list
          List<int> trianglesForColor;
          if (!colors.TryGetValue(color, out trianglesForColor))
            trianglesForColor = colors[color] = new List<int>();
          trianglesForColor.AddRange(tri);
        }

        if (cancel)
          break;

        // make a new mesh for each color
        int colorIndex = 0;
        count = 0;
        foreach (var color in colors.Keys) {
          if (++count > PROGRESS_FREQUENCY) {
            count = 0;
            cancel = EditorUtility.DisplayCancelableProgressBar("Separating sketch", "Processing " + mesh.name, (float)colorIndex / (float)colors.Keys.Count);
            if (cancel) break;
          }
          // Clone the gameobject with the mesh
          var newObj = GameObject.Instantiate(m.gameObject, m.transform.position, m.transform.rotation) as GameObject;
          newObj.name = string.Format("{0} {1}", m.name, colorIndex);
          newObj.transform.SetParent(m.transform.parent, true);
          Undo.RegisterCreatedObjectUndo(newObj, "Separate sketch by color");

          // get the subset of triangles for this color and make a new mesh out of it. TODO: only use the vertices used by the triangles
          var newMesh = GetMeshSubset(mesh, colors[color].ToArray());
          newObj.GetComponent<MeshFilter>().mesh = newMesh;
          colorIndex++;
        }
        Undo.DestroyObjectImmediate(m.gameObject);
      }
      // Delete the original object?
      Undo.DestroyObjectImmediate(o);
    }
    if (!cancel) {
      // Select the newly created objects
      Selection.objects = newSelection.ToArray();
    } else {
      Undo.RevertAllInCurrentGroup();
    }
    EditorUtility.ClearProgressBar();
  }
예제 #19
0
		//when selected
		public void OnSceneGUI ()
		{	
			if (script == null) script = (MapMagic)target;
			MapMagic.instance = script;
			if (!script.enabled) return;

			//checking removed terrains
			foreach (Chunk chunk in script.chunks.All())
				if (chunk.terrain == null) script.chunks.Remove(chunk.coord);
			

			#region Drawing Selection

			//drawing frames
			if (Event.current.type == EventType.Repaint)
			foreach(Chunk chunk in MapMagic.instance.chunks.All())
			{
				Handles.color = nailColor*0.8f;
				if (chunk.locked) Handles.color = lockColor*0.8f;
				DrawSelectionFrame(chunk.coord, 5f);
			}

			#endregion
		

			#region Selecting terrains
			if (selectionMode!=SelectionMode.none)
			{
				//disabling selection
				HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

				//finding aiming ray
				float pixelsPerPoint = 1;
				#if UNITY_5_4_OR_NEWER 
				pixelsPerPoint = EditorGUIUtility.pixelsPerPoint;
				#endif

				SceneView sceneview = UnityEditor.SceneView.lastActiveSceneView;
				if (sceneview==null || sceneview.camera==null) return;
				
				Vector2 mousePos = Event.current.mousePosition;
				mousePos = new Vector2(mousePos.x/sceneview.camera.pixelWidth, 1f/pixelsPerPoint - mousePos.y/sceneview.camera.pixelHeight) * pixelsPerPoint;
				Ray aimRay = sceneview.camera.ViewportPointToRay(mousePos);

				//aiming terrain or empty place
				Vector3 aimPos = Vector3.zero;
				RaycastHit hit;
				if (Physics.Raycast(aimRay, out hit, Mathf.Infinity)) aimPos = hit.point;
				else
				{
					aimRay.direction = aimRay.direction.normalized;
					float aimDist = aimRay.origin.y / (-aimRay.direction.y);
					aimPos = aimRay.origin + aimRay.direction*aimDist;
				}
				aimPos -= MapMagic.instance.transform.position;

				Coord aimCoord = aimPos.FloorToCoord(MapMagic.instance.terrainSize);

				if (selectionMode == SelectionMode.nailing && !Event.current.alt)
				{
					//drawing selection frame
					Handles.color = nailColor;
					DrawSelectionFrame(aimCoord, width:5f);

					//selecting / unselecting
					if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
					{
						if (MapMagic.instance.chunks[aimCoord]==null) //if obj not exists - nail
						{
							Undo.RegisterFullObjectHierarchyUndo(MapMagic.instance, "MapMagic Pin Terrain");
							MapMagic.instance.chunks.Create(aimCoord, script, pin:true); 
							//MapMagic.instance.terrains.maxCount++;
						}
						else 
						{
							Terrain terrain = MapMagic.instance.chunks[aimCoord].terrain;
							if (terrain != null) Undo.DestroyObjectImmediate(terrain.gameObject);
							Undo.RecordObject(MapMagic.instance, "MapMagic Unpin Terrain");
							MapMagic.instance.setDirty = !MapMagic.instance.setDirty;

							MapMagic.instance.chunks.Remove(aimCoord);
							//MapMagic.instance.chunks[aimCoord].pinned = false;
							//MapMagic.instance.terrains.maxCount--;
						}
						//if (MapMagic.instance.terrains.maxCount < MapMagic.instance.terrains.nailedHashes.Count+4) MapMagic.instance.terrains.maxCount = MapMagic.instance.terrains.nailedHashes.Count+4;
						//EditorUtility.SetDirty(MapMagic.instance); //already done via undo
					}
				}

				if (selectionMode == SelectionMode.locking  && !Event.current.alt)
				{
					Chunk aimedTerrain = MapMagic.instance.chunks[aimCoord];
					if (aimedTerrain != null)
					{
						//drawing selection frame
						Handles.color = lockColor;
						DrawSelectionFrame(aimCoord, width:5f);

						//selecting / unselecting
						if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
						{
							Undo.RecordObject(MapMagic.instance, "MapMagic Lock Terrain");
							MapMagic.instance.setDirty = !MapMagic.instance.setDirty;

							aimedTerrain.locked = !aimedTerrain.locked;
							//EditorUtility.SetDirty(MapMagic.instance); //already done via undo
						}
					}
				}

				if (selectionMode == SelectionMode.exporting && !Event.current.alt)
				{
					Chunk aimedTerrain = MapMagic.instance.chunks[aimCoord];
					if (aimedTerrain != null)
					{
						//drawing selection frame
						Handles.color = exportColor;
						DrawSelectionFrame(aimCoord, width:5f);

						//exporting
						if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
						{
							string path= UnityEditor.EditorUtility.SaveFilePanel(
										"Export Terrain Data",
										"",
										"TerrainData.asset", 
										"asset");
							if (path!=null && path.Length!=0)
							{
								path = path.Replace(Application.dataPath, "Assets");
								if (!path.Contains("Assets")) { Debug.LogError("MapMagic: Path is out of the Assets folder"); return; }
								if (AssetDatabase.LoadAssetAtPath(path, typeof(TerrainData)) as TerrainData == aimedTerrain.terrain.terrainData) { Debug.Log("MapMagic: this terrain was already exported at the given path"); return; }
     
								Terrain terrain = aimedTerrain.terrain;
								float[,,] splats = terrain.terrainData.GetAlphamaps(0,0,terrain.terrainData.alphamapResolution, terrain.terrainData.alphamapResolution);
								//else splats = new float[terrain.terrainData.alphamapResolution,terrain.terrainData.alphamapResolution,1];

								if (terrain.terrainData.alphamapLayers==1 && terrain.terrainData.alphamapTextures[0].width==2)
								{
									terrain.terrainData.splatPrototypes = new SplatPrototype[0];
									terrain.terrainData.SetAlphamaps(0,0,new float[0,0,0]);
								}
     
								AssetDatabase.DeleteAsset(path);

								if (AssetDatabase.Contains(terrain.terrainData)) 
								{
									AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(terrain.terrainData),path);
									terrain.terrainData = AssetDatabase.LoadAssetAtPath(path, typeof(TerrainData)) as TerrainData;
									if (terrain.GetComponent<TerrainCollider>()!=null) terrain.GetComponent<TerrainCollider>().terrainData = terrain.terrainData;
								}
								else AssetDatabase.CreateAsset(terrain.terrainData, path);

								terrain.terrainData.SetAlphamaps(0,0,splats);

								AssetDatabase.SaveAssets();
							}
						}
					}
				}
				
				//redrawing scene by moving temp object
				if (script.sceneRedrawObject==null) { script.sceneRedrawObject = new GameObject(); script.sceneRedrawObject.hideFlags = HideFlags.HideInHierarchy; }
				script.sceneRedrawObject.transform.position = aimPos;
			}
			#endregion
		

		}
예제 #20
0
    static void OnSceneGUI(SceneView sceneview)
    {
        int i, j;

        if (cmquad != null)
        {
            if (cmquad.transform.childCount <= 0)
            {
                //double checks there is at least 1 layer inside of cmquad.
                AddLayer();
                ResetLayers();
            }

            if (Event.current.type == EventType.Layout)
            {
                HandleUtility.AddDefaultControl(
                    GUIUtility.GetControlID(
                        window.GetHashCode(),
                        FocusType.Passive));
            }

            e = Event.current;

            Ray        ray = HandleUtility.GUIPointToWorldRay(e.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity))
            {
                //Draw gui elements in scene based on mouse position
                Handles.BeginGUI();
                Handles.color = Color.white;
                Handles.Label(cmCurPos, " ", EditorStyles.boldLabel);

                if ((cmCurPos.x != drawBox.x || cmCurPos.y != drawBox.y) && curTool == 2)
                {
                    if (cmCurPos.x >= drawBox.x)
                    {
                        if (cmCurPos.y <= drawBox.y)
                        {
                            Handles.DrawLine(new Vector3(drawBox.x, drawBox.y + 1, 0), new Vector3(cmCurPos.x + 1, drawBox.y + 1, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, drawBox.y + 1, 0), new Vector3(cmCurPos.x + 1, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, cmCurPos.y, 0), new Vector3(drawBox.x, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(drawBox.x, cmCurPos.y, 0), new Vector3(drawBox.x, drawBox.y + 1, 0));
                        }
                        else
                        {
                            Handles.DrawLine(new Vector3(drawBox.x, drawBox.y, 0), new Vector3(cmCurPos.x + 1, drawBox.y, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, drawBox.y, 0), new Vector3(cmCurPos.x + 1, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, cmCurPos.y, 0), new Vector3(drawBox.x, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(drawBox.x, cmCurPos.y, 0), new Vector3(drawBox.x, drawBox.y, 0));
                        }
                    }
                    else
                    {
                        if (cmCurPos.y <= drawBox.y)
                        {
                            Handles.DrawLine(new Vector3(drawBox.x + 1, drawBox.y + 1, 0), new Vector3(cmCurPos.x + 1, drawBox.y + 1, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, drawBox.y + 1, 0), new Vector3(cmCurPos.x + 1, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, cmCurPos.y, 0), new Vector3(drawBox.x + 1, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(drawBox.x + 1, cmCurPos.y, 0), new Vector3(drawBox.x + 1, drawBox.y + 1, 0));
                        }
                        else
                        {
                            Handles.DrawLine(new Vector3(drawBox.x + 1, drawBox.y, 0), new Vector3(cmCurPos.x + 1, drawBox.y, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, drawBox.y, 0), new Vector3(cmCurPos.x + 1, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(cmCurPos.x + 1, cmCurPos.y, 0), new Vector3(drawBox.x + 1, cmCurPos.y, 0));
                            Handles.DrawLine(new Vector3(drawBox.x + 1, cmCurPos.y, 0), new Vector3(drawBox.x + 1, drawBox.y, 0));
                        }
                    }
                }
                else
                {
                    Handles.DrawLine(cmCurPos + new Vector3(0, 0, 0), cmCurPos + new Vector3(1, 0, 0));
                    Handles.DrawLine(cmCurPos + new Vector3(1, 0, 0), cmCurPos + new Vector3(1, 1, 0));
                    Handles.DrawLine(cmCurPos + new Vector3(1, 1, 0), cmCurPos + new Vector3(0, 1, 0));
                    Handles.DrawLine(cmCurPos + new Vector3(0, 1, 0), cmCurPos + new Vector3(0, 0, 0));
                }
                Handles.EndGUI();

                if (e.isMouse)
                {
                    if (e.button == 0 && (e.type == EventType.MouseUp || e.type == EventType.MouseDrag))
                    {
                        if (curTool == 0)
                        {
                            GameObject tmpObj = GenerateTile(hit.point.x, hit.point.y);
                            Undo.RegisterCreatedObjectUndo(tmpObj, "Created Tile");
                            Sprite[] tmpCurSprite = new Sprite[cmCurSprite.Count];
                            cmCurSprite.CopyTo(tmpCurSprite);

                            if (tmpCurSprite.Length > 0)
                            {
                                tmpObj.GetComponent <SpriteRenderer>().sprite = tmpCurSprite[UnityEngine.Random.Range((int)0, (int)tmpCurSprite.Length)];
                                tmpObj.transform.localPosition = new Vector3(Mathf.Floor(hit.point.x) + .5f, Mathf.Floor(hit.point.y) + .5f, layers[selectedLayer].transform.position.z);
                            }
                            else
                            {
                                Debug.LogWarning("Tile not selected for painting. Please select a tile to paint.");
                            }
                        }
                        else if (curTool == 1)
                        {
                            Transform tmpObj = layers[selectedLayer].Find("Tile|" + (Mathf.Floor(hit.point.x) + .5f) + "|" + (Mathf.Floor(hit.point.y) + .5f));
                            if (tmpObj != null)
                            {
                                Undo.DestroyObjectImmediate(tmpObj.gameObject);
                            }
                        }
                        else if (curTool == 2)
                        {
                            if (e.type == EventType.MouseUp)
                            {
                                Vector2 distance;
                                bool    drawLeft, drawUp;


                                if (drawBox.x >= hit.point.x)
                                {
                                    distance.x = drawBox.x - hit.point.x;
                                    drawLeft   = true;
                                }
                                else
                                {
                                    distance.x = hit.point.x - drawBox.x;
                                    drawLeft   = false;
                                }

                                if (drawBox.y >= hit.point.y)
                                {
                                    distance.y = drawBox.y - hit.point.y;
                                    drawUp     = false;
                                }
                                else
                                {
                                    distance.y = hit.point.y - drawBox.y;

                                    distance.y -= 1;
                                    drawUp      = true;
                                }

                                if (cmCurPos.y > drawBox.y)
                                {
                                    distance.y -= 1;
                                }


                                for (i = 0; i <= distance.x; i++)
                                {
                                    for (j = 0; j <= Mathf.Ceil(distance.y); j++)
                                    {
                                        int curI = i;
                                        int curJ = j;
                                        if (drawLeft)
                                        {
                                            curI = -curI;
                                        }
                                        if (drawUp)
                                        {
                                            curJ = -curJ;
                                        }
                                        if (cmCurSprite != null)
                                        {
                                            GameObject tmpObj = GenerateTile(drawBox.x + curI, drawBox.y - curJ);
                                            Undo.RegisterCreatedObjectUndo(tmpObj, "Created Tiles in Box");
                                            Sprite[] tmpCurSprite = new Sprite[cmCurSprite.Count];
                                            cmCurSprite.CopyTo(tmpCurSprite);
                                            tmpObj.GetComponent <SpriteRenderer>().sprite = tmpCurSprite[UnityEngine.Random.Range((int)0, (int)tmpCurSprite.Length)];
                                            tmpObj.transform.localPosition = new Vector3(Mathf.Floor(drawBox.x + curI) + .5f, Mathf.Floor(drawBox.y - curJ) + .5f, layers[selectedLayer].transform.position.z);
                                        }
                                        else
                                        {
                                            Debug.LogWarning("No tiles selected.");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (e.button == 0 && e.type == EventType.MouseDown)
                    {
                        drawBox.x = Mathf.Floor(hit.point.x);
                        drawBox.y = Mathf.Floor(hit.point.y);
                    }
                    else if (e.type == EventType.MouseMove)
                    {
                        drawBox.x = Mathf.Floor(hit.point.x);
                        drawBox.y = Mathf.Floor(hit.point.y);
                    }
                }
                cmCurPos.x = (float)Mathf.Floor(hit.point.x);
                cmCurPos.y = (float)Mathf.Floor(hit.point.y);
                if (curLayer != null)
                {
                    cmCurPos.z = curLayer.transform.position.z - 1;
                }
                else
                {
                    cmCurPos.z = 0;
                }
            }
        }
        else
        {
            ResetManager();
        }
        SceneView.RepaintAll();
    }
예제 #21
0
        public static void ModifyAction(ActionListAsset _target, AC.Action _action, string callback)
        {
            ActionsManager actionsManager = AdvGame.GetReferences().actionsManager;

            if (actionsManager == null)
            {
                return;
            }

            int i = -1;

            if (_action != null && _target.actions.IndexOf(_action) > -1)
            {
                i = _target.actions.IndexOf(_action);
            }

            switch (callback)
            {
            case "Enable":
                Undo.RecordObject(_target, "Enable action");
                _target.actions [i].isEnabled = true;
                break;

            case "Disable":
                Undo.RecordObject(_target, "Disable action");
                _target.actions [i].isEnabled = false;
                break;

            case "Cut":
                Undo.RecordObject(_target, "Cut action");
                List <AC.Action> cutList   = new List <AC.Action>();
                AC.Action        cutAction = Object.Instantiate(_action) as AC.Action;
                cutList.Add(cutAction);
                AdvGame.copiedActions = cutList;
                _target.actions.Remove(_action);
                Undo.DestroyObjectImmediate(_action);
                //UnityEngine.Object.DestroyImmediate (_action, true);
                AssetDatabase.SaveAssets();
                break;

            case "Copy":
                List <AC.Action> copyList   = new List <AC.Action>();
                AC.Action        copyAction = Object.Instantiate(_action) as AC.Action;
                copyAction.name = copyAction.name.Replace("(Clone)", "");
                copyList.Add(copyAction);
                AdvGame.copiedActions = copyList;
                break;

            case "Paste after":
                Undo.RecordObject(_target, "Paste actions");
                List <AC.Action> pasteList = AdvGame.copiedActions;
                int j = i + 1;
                foreach (AC.Action action in pasteList)
                {
                    if (action == null)
                    {
                        ACDebug.LogWarning("Error when pasting Action - cannot find original. Did you change scene before pasting? If you need to transfer Actions between scenes, copy them to an ActionList asset first.");
                        continue;
                    }

                    AC.Action pastedAction = Object.Instantiate(action) as AC.Action;
                    pastedAction.name      = pastedAction.name.Replace("(Clone)", "");
                    pastedAction.hideFlags = HideFlags.HideInHierarchy;
                    _target.actions.Insert(j, pastedAction);
                    j++;
                    AssetDatabase.AddObjectToAsset(pastedAction, _target);
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(pastedAction));
                }
                AssetDatabase.SaveAssets();
                break;

            case "Insert after":
                Undo.RecordObject(_target, "Create action");
                ActionListAssetEditor.AddAction(actionsManager.GetDefaultAction(), i + 1, _target);
                break;

            case "Delete":
                Undo.RecordObject(_target, "Delete action");
                _target.actions.Remove(_action);
                Undo.DestroyObjectImmediate(_action);
                //UnityEngine.Object.DestroyImmediate (_action, true);
                AssetDatabase.SaveAssets();
                break;

            case "Move to top":
                Undo.RecordObject(_target, "Move action to top");
                _target.actions.Remove(_action);
                _target.actions.Insert(0, _action);
                break;

            case "Move up":
                Undo.RecordObject(_target, "Move action up");
                _target.actions.Remove(_action);
                _target.actions.Insert(i - 1, _action);
                break;

            case "Move to bottom":
                Undo.RecordObject(_target, "Move action to bottom");
                _target.actions.Remove(_action);
                _target.actions.Insert(_target.actions.Count, _action);
                break;

            case "Move down":
                Undo.RecordObject(_target, "Move action down");
                _target.actions.Remove(_action);
                _target.actions.Insert(i + 1, _action);
                break;
            }
        }
예제 #22
0
        private static KeyValuePair <bool, Actions> PaintHeader(
            GameObject parent,
            SerializedProperty spParentActions,
            ActionsEditor parentActionsEditor)
        {
            KeyValuePair <bool, Actions> returnActions = new KeyValuePair <bool, Actions>(false, null);

            EditorGUILayout.BeginHorizontal();

            EditorGUI.BeginDisabledGroup(PrefabUtility.GetPrefabType(parent) == PrefabType.Prefab);
            if (GUILayout.Button("Create Actions", EditorStyles.miniButton))
            {
                int option = 2;
                if (parentActionsEditor != null)
                {
                    option = EditorUtility.DisplayDialogComplex(
                        MSG_OVERWRITE_TITLE,
                        MSG_OVERWRITE_DESCR,
                        "Replace",
                        "Cancel",
                        "Keep both"
                        );
                }

                if (option == 0)
                {
                    Undo.DestroyObjectImmediate(parentActionsEditor.instance.gameObject);
                    parentActionsEditor = null;
                }

                if (option != 1)
                {
                    returnActions = new KeyValuePair <bool, Actions>(
                        true, ActionsEditor.CreateActions(parent, "Actions")
                        );
                }
            }
            EditorGUI.EndDisabledGroup();

            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(spParentActions, GUIContent.none);
            if (EditorGUI.EndChangeCheck())
            {
                returnActions = new KeyValuePair <bool, Actions>(
                    true,
                    spParentActions.objectReferenceValue as Actions
                    );
            }

            EditorGUILayout.EndHorizontal();

            if (parentActionsEditor == null)
            {
                EditorGUILayout.HelpBox(
                    MSG_EMPTY_ACTIONS,
                    MessageType.None
                    );

                return(returnActions);
            }

            parentActionsEditor.OnInspectorGUI();
            return(returnActions);
        }
예제 #23
0
    static void ConvertSpriteType(GameObject go, System.Type targetType)
    {
        tk2dBaseSprite spr = go.GetComponent <tk2dBaseSprite>();

        System.Type sourceType = spr.GetType();

        if (sourceType != targetType)
        {
            tk2dBatchedSprite batchedSprite = new tk2dBatchedSprite();
            tk2dStaticSpriteBatcherEditor.FillBatchedSprite(batchedSprite, go);
            if (targetType == typeof(tk2dSprite))
            {
                batchedSprite.type = tk2dBatchedSprite.Type.Sprite;
            }
            else if (targetType == typeof(tk2dTiledSprite))
            {
                batchedSprite.type = tk2dBatchedSprite.Type.TiledSprite;
            }
            else if (targetType == typeof(tk2dSlicedSprite))
            {
                batchedSprite.type = tk2dBatchedSprite.Type.SlicedSprite;
            }
            else if (targetType == typeof(tk2dClippedSprite))
            {
                batchedSprite.type = tk2dBatchedSprite.Type.ClippedSprite;
            }

#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
            if (spr.collider != null)
            {
                Object.DestroyImmediate(spr.collider);
            }
            Object.DestroyImmediate(spr, true);
#else
            {
                Collider[] colliders = spr.GetComponents <Collider>();
                foreach (Collider c in colliders)
                {
                    Undo.DestroyObjectImmediate(c);
                }
                Collider2D[] collider2Ds = spr.GetComponents <Collider2D>();
                foreach (Collider2D c in collider2Ds)
                {
                    Undo.DestroyObjectImmediate(c);
                }
            }
            Undo.DestroyObjectImmediate(spr);
#endif

            bool sourceHasDimensions = sourceType == typeof(tk2dSlicedSprite) || sourceType == typeof(tk2dTiledSprite);
            bool targetHasDimensions = targetType == typeof(tk2dSlicedSprite) || targetType == typeof(tk2dTiledSprite);

            // Some minor fixups
            if (!sourceHasDimensions && targetHasDimensions)
            {
                batchedSprite.Dimensions = new Vector2(100, 100);
            }
            if (targetType == typeof(tk2dClippedSprite))
            {
                batchedSprite.ClippedSpriteRegionBottomLeft = Vector2.zero;
                batchedSprite.ClippedSpriteRegionTopRight   = Vector2.one;
            }
            if (targetType == typeof(tk2dSlicedSprite))
            {
                batchedSprite.SlicedSpriteBorderBottomLeft = new Vector2(0.1f, 0.1f);
                batchedSprite.SlicedSpriteBorderTopRight   = new Vector2(0.1f, 0.1f);
            }

            tk2dStaticSpriteBatcherEditor.RestoreBatchedSprite(go, batchedSprite);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
            {
                tk2dBaseSprite tmpSprite = go.GetComponent <tk2dBaseSprite>();
                if (tmpSprite != null)
                {
                    Undo.RegisterCreatedObjectUndo(tmpSprite, "Convert Sprite Type");
                }
            }
#endif
        }
    }
        // This is called for each window that your tool is active in. Put the functionality of your tool here.
        public override void OnToolGUI(EditorWindow window)
        {
            var p        = Event.current.mousePosition;
            var rawEvent = Event.current.rawType;

            if (rawEvent == EventType.MouseMove || rawEvent == EventType.MouseDrag)
            {
                // PaletteCommon.brush.UpdatePosition(p);
                // var p = Event.current.mousePosition;
                // currentBrush.transform.position = p;

                var ray      = HandleUtility.GUIPointToWorldRay(p);
                var position = ray.origin;
                position.z = 0;
                PaletteCommon.brush.UpdatePosition(position);
            }

            if (Event.current.rawType == EventType.KeyDown && Event.current.keyCode == KeyCode.E)
            {
                if (PaletteCommon.mode == PaletteToolMode.Paint)
                {
                    PaletteCommon.mode = PaletteToolMode.Erase;
                    PaletteCommon.brush?.DestroyPreview();
                    Event.current.Use();
                }
                else
                {
                    PaletteCommon.mode = PaletteToolMode.Paint;
                    if (PaletteCommon.brush != null && !PaletteCommon.selection.IsEmpty)
                    {
                        PaletteCommon.brush.CreatePreview(PaletteCommon.selection.selection);
                    }
                    Event.current.Use();
                }
            }

            // if (Event.current.type == EventType.ScrollWheel)
            // {
            //     HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
            //     PaletteCommon.brush.CreatePreview(PaletteCommon.selection.SelectedPrefabs);
            //     Event.current.Use();
            // }

            // This is used somehow to avoid default scene view controls to consume Event MouseDrag so we
            // can use it to paint.
            if (Event.current.type == EventType.Layout && leftMouseButtonDown)
            {
                // HandleUtility.AddDefaultControl(0);
                HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
                GUIUtility.hotControl = GUIUtility.GetControlID(FocusType.Passive);
            }

            // Debug.Log($"{Event.current.rawType}, {Event.current.type}");

            // TODO: repeat delay/distance.

            var painting = rawEvent == EventType.MouseDown && Event.current.button == 0;

            painting = painting || rawEvent == EventType.MouseDrag;

            if (rawEvent == EventType.MouseDown && Event.current.button == 0)
            {
                leftMouseButtonDown = true;
            }

            if (rawEvent == EventType.MouseUp && Event.current.button == 0)
            {
                leftMouseButtonDown = false;
            }

            if (painting)
            {
                if (PaletteCommon.mode == PaletteToolMode.Paint)
                {
                    if (PaletteCommon.brush != null && !PaletteCommon.selection.IsEmpty)
                    {
                        PaletteCommon.brush.Paint();
                        if (PaletteCommon.brush.RegenerateOnPaint)
                        {
                            PaletteCommon.brush.CreatePreview(PaletteCommon.selection.selection);
                        }
                        Event.current.Use();
                    }
                }
                else if (PaletteCommon.mode == PaletteToolMode.Erase)
                {
                    var go = HandleUtility.PickGameObject(p, true);

                    // check if it is a prefab instance since now we instantiate prefabs (but that could change)
                    // TODO: check if object in root, etc.
                    if (go != null && PrefabUtility.GetPrefabInstanceStatus(go) != PrefabInstanceStatus.NotAPrefab)
                    {
                        Undo.DestroyObjectImmediate(go);
                        Event.current.Use();
                    }
                }
            }
        }
예제 #25
0
        private void OnGUI()
        {
            EditorGUILayout.HelpBox(
                "This tool replaces the currently selected GameObjects with instances of the specified Prefab.",
                MessageType.None);
            EditorGUILayout.Space();

            GUILayout.Label("Selections:", EditorStyles.boldLabel);
            EditorGUILayout.BeginVertical();
            foreach (var selectedObject in Selection.gameObjects)
            {
                GUILayout.Label(selectedObject.name);
            }

            EditorGUILayout.EndVertical();

            GUILayout.Label("Prefab Object", EditorStyles.boldLabel);
            this.prefabObject = EditorGUILayout.ObjectField(this.prefabObject, typeof(GameObject), true) as GameObject;

            if (!IsGameObjectPrefab(this.prefabObject))
            {
                EditorGUILayout.HelpBox("GameObject is not a Prefab or Prefab Instance", MessageType.Error);
                return;
            }

            if (Selection.activeTransform == null)
            {
                EditorGUILayout.HelpBox("No GameObjects selected", MessageType.Warning);
                return;
            }

            if (GUILayout.Button("Replace Selected"))
            {
                if (this.prefabObject != null)
                {
                    Transform transformToSelect = null;
                    foreach (Transform transformToCopy in Selection.transforms)
                    {
                        GameObject instanceObj = null;
                        GameObject prefab      = PrefabUtility.GetPrefabParent(this.prefabObject) as GameObject;
                        var        prefabType  = PrefabUtility.GetPrefabType(this.prefabObject);

                        if (prefabType == PrefabType.PrefabInstance)
                        {
                            // Copy instance settings into selected object if the selection is a prefab instance
                            instanceObj = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
                            PrefabUtility.SetPropertyModifications(
                                instanceObj,
                                PrefabUtility.GetPropertyModifications(this.prefabObject));
                        }
                        else if (prefabType == PrefabType.Prefab)
                        {
                            // Instantiate a new prefab
                            instanceObj = (GameObject)PrefabUtility.InstantiatePrefab(this.prefabObject);
                        }
                        else
                        {
                            Debug.LogError("Supplied GameObject is of an unrecognized type.");
                            return;
                        }

                        Undo.RegisterCreatedObjectUndo(instanceObj, "created prefab");

                        // Apply previous transform settings to the new one
                        Transform createdTransform = instanceObj.transform;
                        createdTransform.position   = transformToCopy.position;
                        createdTransform.rotation   = transformToCopy.rotation;
                        createdTransform.localScale = transformToCopy.localScale;
                        createdTransform.parent     = transformToCopy.parent;

                        // Keep the old name
                        createdTransform.name = transformToCopy.name;

                        // Restore sibling index
                        createdTransform.SetSiblingIndex(transformToCopy.GetSiblingIndex());

                        // Flag transform to reselect
                        if (transformToCopy == Selection.activeTransform)
                        {
                            transformToSelect = createdTransform;
                        }
                    }

                    // Destroy old game objects
                    foreach (GameObject go in Selection.gameObjects)
                    {
                        Undo.DestroyObjectImmediate(go);
                    }

                    if (transformToSelect != null)
                    {
                        Selection.activeTransform = transformToSelect;
                    }
                }
            }
        }
예제 #26
0
        public static bool SetOutfit(Body body, Outfit outfit, float repoOffset = 0,
                                     RemoveActionType removeType = RemoveActionType.Undefined, bool singleUndo = true,
                                     string undoLabel            = "Set Outfit")
        {
            // Design note:  It would be much simpler to just remove and add in separate transactions.  But that
            // sends the wrong type of event to observers, so have to go the messy route in order to properly
            // mimic runtime behavior.

            // Validations

            if (!CheckValidAction(body))
            {
                return(false);
            }

            if (outfit == body.Outfit)
            {
                Debug.LogWarning("No action taken. Outfit is the same as the body's current outfit: "
                                 + (outfit ? outfit.name : "null"), body);
                return(true);  // This is the correct behavior.
            }

            if (outfit && outfit.IsManaged)
            {
                Debug.LogError("Can't set outfit.  The outfit is already managed by: " + outfit.Owner.name, body);
                return(false);
            }

            // Keep last since it may involve a dialog box.
            Transform origParent = null;

            if (body.Outfit)
            {
                removeType = GetRemoveType(body, removeType);
                if (removeType == RemoveActionType.Cancel)
                {
                    return(false);
                }

                origParent = body.Outfit.transform.parent;
            }

            // Prepare for transaction.

            if (singleUndo)
            {
                Undo.IncrementCurrentGroup();
            }

            bool      isNew        = false;
            Transform outfitParent = null;

            if (outfit)
            {
                isNew = AssetDatabase.Contains(outfit);
                if (isNew)
                {
                    var name = outfit.name;
                    outfit      = outfit.Instantiate();
                    outfit.name = name;
                    // Will register the undo after success has been determined.
                }
                else
                {
                    Undo.RecordObjects(Outfit.UnsafeGetUndoObjects(outfit).ToArray(), undoLabel);
                }

                outfitParent = outfit.transform.parent;
            }

            Undo.RecordObjects(Body.UnsafeGetUndoObjects(body).ToArray(), undoLabel);

            // Set the outfit.

            var orig    = body.SetOutfit(outfit);
            var success = (orig != outfit);

            if (success)
            {
                if (orig)
                {
                    // Finalize the original outfit.

                    orig.transform.parent = origParent;
                    Undo.SetTransformParent(orig.transform, null, undoLabel);

                    if (removeType == RemoveActionType.RemoveAndDestroy)
                    {
                        orig.Destroy(DestroyType.GameObject, true);
                        Undo.DestroyObjectImmediate(orig.gameObject);
                    }
                    else if (repoOffset > 0)
                    {
                        // This extra call is needed, otherwise only **part** of the translation is recorded.  The
                        // problem might be due to the change in the parent.  Anyway, more fun with undo...
                        Undo.RecordObject(orig.transform, undoLabel);
                        orig.transform.position += body.transform.right * repoOffset;
                    }
                }

                if (outfit)
                {
                    // Finalize the outfit that was set.

                    if (isNew)
                    {
                        Undo.RegisterCreatedObjectUndo(outfit.gameObject, undoLabel);
                    }

                    var parent = outfit.transform.parent;
                    outfit.transform.parent = outfitParent;
                    Undo.SetTransformParent(outfit.transform, parent, undoLabel);

                    if (body is StandardBody)
                    {
                        // HACK: Addition of body as outfit observer is not being recorded for serialization.
                        // This fixes it until the cause and proper fix can be determined.
                        StandardOutfitEditor.AddObserverWithUndo(outfit, (StandardBody)body);
                    }
                }

                success = true;
            }
            else
            {
                if (isNew)
                {
                    outfit.gameObject.SafeDestroy();
                }

                success = false;
            }

            if (singleUndo)
            {
                Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
            }

            return(success);
        }
예제 #27
0
    void GOToolGUI(Transform t)
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Selected Object", GUILayout.MaxWidth(100.0f));
        EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        string n = EditorGUILayout.TextField(t.name);

        if (GUILayout.Button("Deselect"))
        {
            Selection.activeGameObject = null;
        }
        EditorGUILayout.EndHorizontal();
        if (n != t.name)
        {
            t.name = n;
        }

        EditorGUILayout.Space();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Position", GUILayout.MaxWidth(50.0f));
        t.localPosition = EditorGUILayout.Vector3Field("", t.localPosition);
        EditorGUILayout.EndHorizontal();


        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Rotation", GUILayout.MaxWidth(50.0f));
        t.localRotation = Quaternion.Euler(EditorGUILayout.Vector3Field("", t.localRotation.eulerAngles));
        EditorGUILayout.EndHorizontal();


        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Scale", GUILayout.MaxWidth(50.0f));
        t.localScale = EditorGUILayout.Vector3Field("", t.localScale);
        EditorGUILayout.EndHorizontal();


        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Reset Position"))
        {
            t.localPosition = Vector3.zero;
        }
        if (GUILayout.Button("Reset Rotation"))
        {
            t.localRotation = Quaternion.identity;
            rotMover        = t.position + (t.forward * 1.5f);
        }
        if (GUILayout.Button("Reset Scale"))
        {
            t.localScale = Vector3.one;
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Space();

        EditorGUILayout.Space();

        Component[] c = t.GetComponents <Component>();

        for (int i = 0; i < c.Length; i++)
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Button(c[i].GetType().Name);
            if (GUILayout.Button("↑", GUILayout.Width(20.0f)))
            {
                UnityEditorInternal.ComponentUtility.MoveComponentUp(c[i]);
            }
            if (GUILayout.Button("↓", GUILayout.Width(20.0f)))
            {
                UnityEditorInternal.ComponentUtility.MoveComponentDown(c[i]);
            }
            if (GUILayout.Button("X", GUILayout.Width(20.0f)))   /*if (c[i].GetType() != typeof(Transform))*/
            {
            {
                Undo.DestroyObjectImmediate(c[i]);
            }
        }
        EditorGUILayout.EndHorizontal();
    }
    EditorGUILayout.Space();

    EditorGUILayout.BeginHorizontal();
    EditorGUILayout.LabelField("Rotate towards point", GUILayout.MaxWidth(125.0f));
    EditorGUI.BeginChangeCheck();
    rotateToggle = EditorGUILayout.Toggle(rotateToggle);
    if (EditorGUI.EndChangeCheck())
    {
        rotMover = t.position + (t.forward * 1.5f);
    }
    EditorGUILayout.EndHorizontal();

    EditorGUILayout.Space();

    if (GUILayout.Button("Rename Children"))
    {
        ExamplePopup.InitPopup(t);
    }

    EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);

    EditorGUILayout.Space();
}
예제 #28
0
    public override void OnInspectorGUI()
    {
        Meshcombinervtwo myScript = (Meshcombinervtwo)target;
        GUIStyle         style    = new GUIStyle(GUI.skin.box);

        style.normal.background = MakeTex(2, 2, new Color(1, 1, 0, .6f));

        serializedObject.Update();

        EditorGUILayout.LabelField("");

        if (SeeInspector.boolValue)
        {
            DrawDefaultInspector();
        }

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("See Variables : ", GUILayout.Width(90));
        EditorGUILayout.PropertyField(SeeInspector, new GUIContent(""));
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.LabelField("");

        EditorGUILayout.HelpBox("\n" + "Combine Meshes : " +
                                "\n" +
                                "\n1 - GameObject inside this gameObject are combine." +
                                "\n" +
                                "\nAll the gameObjects with the same material are combine in a single mesh." +
                                "\n" +
                                "\nCombining Process could take time if there are a lots of gameObjects to combine." +
                                "\n" +
                                "\n2 - Press button Combine to start the process" +
                                "\n", MessageType.Info);


        EditorGUILayout.BeginVertical(style);

        EditorGUILayout.LabelField("");
        if (!CombineDone.boolValue)
        {
            if (GUILayout.Button("Combine"))
            {
                b_Combine = true;
            }
        }
        else
        {
            if (GUILayout.Button("Reset"))
            {
                b_Uncombine = true;
            }
        }
        EditorGUILayout.LabelField("");
        EditorGUILayout.EndVertical();
        //

        EditorGUILayout.HelpBox("3 - After the combining process gameObjects are created for each material inside this folder.", MessageType.Info);
        EditorGUILayout.HelpBox("INFO 1 : Mesh renderer are disabled for the gameObjects that have been used in the combining process." +
                                "\nINFO 2 : After combinig process, colliders stay activated.", MessageType.Info);


        EditorGUILayout.LabelField("");
        EditorGUILayout.LabelField("");
        style.normal.background = MakeTex(2, 2, new Color(.5f, .8f, 0, .3f));
        EditorGUILayout.BeginVertical(style);
        EditorGUILayout.HelpBox("(Optional) : Exclude gameObjects with specific TAG", MessageType.Info);
        EditorGUILayout.LabelField("");

        if (GUILayout.Button("Add new tag"))
        {
            b_AddTag = true;
        }
        EditorGUILayout.LabelField("");

        EditorGUILayout.LabelField("Exclude gameObjects with these Tags :");

        for (int i = 0; i < myScript.list_Tags.Count; i++)
        {
            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.PropertyField(list_Tags.GetArrayElementAtIndex(i), new GUIContent(""));
            if (GUILayout.Button("-", GUILayout.Width(20)))
            {
                b_DeleteTag = true;
                deleteNum   = i;
                break;
            }
            EditorGUILayout.EndHorizontal();
        }
        EditorGUILayout.EndVertical();

        serializedObject.ApplyModifiedProperties();

        if (b_Combine)
        {
            Undo.RegisterCompleteObjectUndo(myScript, "MeshCombiner" + myScript.gameObject.name);
            myScript.CombineDone = true;
            Component[] ChildrenMesh = myScript.GetComponentsInChildren(typeof(MeshRenderer), true);

            myScript.list_Materials.Clear();

            foreach (MeshRenderer child in ChildrenMesh)                                        // Find all the different materials
            {
                myScript.list_Materials.Add(child.sharedMaterial);
            }

            for (int i = 0; i < myScript.list_Materials.Count; i++)                                     // remove materials using multiple time
            {
                for (int k = 0; k < myScript.list_Materials.Count; k++)
                {
                    if (k != i && myScript.list_Materials[i] == myScript.list_Materials[k])
                    {
                        myScript.list_Materials[k] = null;
                    }
                }
            }

            List <Material> Tmp_list_Materials = new List <Material>();                                 // List of materials

            for (int i = 0; i < myScript.list_Materials.Count; i++)                                     // Update Materials List
            {
                if (myScript.list_Materials[i])
                {
                    Tmp_list_Materials.Add(myScript.list_Materials[i]);
                }
            }

            myScript.list_Materials.Clear();

            for (int i = 0; i < Tmp_list_Materials.Count; i++)                                  // Update Materials List
            {
                myScript.list_Materials.Add(Tmp_list_Materials[i]);
            }

            myScript.list_CreatedObjects.Clear();
            myScript.list_CombineObjects.Clear();

            Quaternion oldRot = myScript.transform.rotation;                                                            // Save the original position and rotation of obj
            Vector3    oldPos = myScript.transform.position;

            myScript.transform.rotation = Quaternion.identity;
            myScript.transform.position = new Vector3(0, 0, 0);

            for (int i = 0; i < myScript.list_Materials.Count; i++)
            {
                CombineMeshes(myScript.list_Materials[i]);
            }

            myScript.transform.rotation = oldRot;
            myScript.transform.position = oldPos;

            b_Combine = false;
        }

        if (b_Uncombine)
        {
            Undo.RegisterCompleteObjectUndo(myScript, "MeshCombiner" + myScript.gameObject.name);
            myScript.CombineDone = false;

            for (int i = 0; i < myScript.list_CombineObjects.Count; i++)
            {
                if (myScript.list_CombineObjects[i] != null)
                {
                    SerializedObject serializedObject3 = new UnityEditor.SerializedObject(myScript.list_CombineObjects[i].gameObject.GetComponents <Renderer>());
                    serializedObject3.Update();
                    SerializedProperty tmpSer2 = serializedObject3.FindProperty("m_Enabled");
                    tmpSer2.boolValue = true;
                    serializedObject3.ApplyModifiedProperties();
                }
            }

            for (int i = 0; i < myScript.list_CreatedObjects.Count; i++)
            {
                if (myScript.list_CreatedObjects[i] != null)
                {
                    Undo.DestroyObjectImmediate(myScript.list_CreatedObjects[i]);
                }
            }

            myScript.list_CreatedObjects.Clear();
            myScript.list_CombineObjects.Clear();
            b_Uncombine = false;
        }

        if (b_AddTag)
        {
            Undo.RegisterCompleteObjectUndo(myScript, "Save" + myScript.gameObject.name);
            myScript.list_Tags.Add("Your Tag");
            b_AddTag = false;
        }

        if (b_DeleteTag)
        {
            Undo.RegisterCompleteObjectUndo(myScript, "Delete" + myScript.gameObject.name);
            myScript.list_Tags.RemoveAt(deleteNum);
            b_DeleteTag = false;
        }
    }
        void SetupChildList()
        {
            float vSpace          = 2;
            float hSpace          = 3;
            float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f;
            float hBigSpace       = EditorGUIUtility.singleLineHeight * 2 / 3;

            mChildList = new UnityEditorInternal.ReorderableList(serializedObject,
                                                                 serializedObject.FindProperty(() => Target.m_ChildCameras),
                                                                 true, true, true, true);

            mChildList.drawHeaderCallback = (Rect rect) =>
            {
                EditorGUI.LabelField(rect, "Virtual Camera Children");
                GUIContent priorityText   = new GUIContent("Priority");
                var        textDimensions = GUI.skin.label.CalcSize(priorityText);
                rect.x    += rect.width - textDimensions.x;
                rect.width = textDimensions.x;
                EditorGUI.LabelField(rect, priorityText);
            };
            mChildList.drawElementCallback
                = (Rect rect, int index, bool isActive, bool isFocused) =>
                {
                rect.y     += vSpace; rect.height = EditorGUIUtility.singleLineHeight;
                rect.width -= floatFieldWidth + hBigSpace;
                SerializedProperty element = mChildList.serializedProperty.GetArrayElementAtIndex(index);
                EditorGUI.PropertyField(rect, element, GUIContent.none);

                float oldWidth = EditorGUIUtility.labelWidth;
                EditorGUIUtility.labelWidth = hBigSpace;
                SerializedObject obj = new SerializedObject(element.objectReferenceValue);
                rect.x += rect.width + hSpace; rect.width = floatFieldWidth + hBigSpace;
                SerializedProperty priorityProp = obj.FindProperty(() => Target.m_Priority);
                EditorGUI.PropertyField(rect, priorityProp, new GUIContent(" ", priorityProp.tooltip));
                EditorGUIUtility.labelWidth = oldWidth;
                obj.ApplyModifiedProperties();
                };
            mChildList.onChangedCallback = (UnityEditorInternal.ReorderableList l) =>
            {
                if (l.index < 0 || l.index >= l.serializedProperty.arraySize)
                {
                    return;
                }
                Object o = l.serializedProperty.GetArrayElementAtIndex(
                    l.index).objectReferenceValue;
                CinemachineVirtualCameraBase vcam = (o != null)
                        ? (o as CinemachineVirtualCameraBase) : null;
                if (vcam != null)
                {
                    vcam.transform.SetSiblingIndex(l.index);
                }
            };
            mChildList.onAddCallback = (UnityEditorInternal.ReorderableList l) =>
            {
                var index = l.serializedProperty.arraySize;
                var vcam  = CinemachineMenu.CreateDefaultVirtualCamera();
                Undo.SetTransformParent(vcam.transform, Target.transform, "");
                vcam.transform.SetSiblingIndex(index);
            };
            mChildList.onRemoveCallback = (UnityEditorInternal.ReorderableList l) =>
            {
                Object o = l.serializedProperty.GetArrayElementAtIndex(
                    l.index).objectReferenceValue;
                CinemachineVirtualCameraBase vcam = (o != null)
                        ? (o as CinemachineVirtualCameraBase) : null;
                if (vcam != null)
                {
                    Undo.DestroyObjectImmediate(vcam.gameObject);
                }
            };
        }
예제 #30
0
        private bool ConstraintTypeGUI(Constraint[] constraints, bool differentTypes)
        {
            var anyUnknownType = constraints.Any(c => c.Type == ConstraintType.Unknown);
            // Reference type is set to unknown if we have multi-select and
            // the types aren't the same. This is to detect if the user has
            // selected some valid type, with the limitation that it's not
            // possible to change to Unknown (that action will be ignored).
            var refType = differentTypes ?
                          ConstraintType.Unknown :
                          constraints[0].Type;

            EditorGUI.showMixedValue = differentTypes;

            var newType = refType;

            using (new GUI.EnabledBlock(!EditorApplication.isPlayingOrWillChangePlaymode)) {
                if (refType == ConstraintType.Unknown)
                {
                    newType = (ConstraintType)EditorGUILayout.EnumPopup(GUI.MakeLabel("Choose type"),
                                                                        refType,
                                                                        InspectorEditor.Skin.Popup);
                }
                else
                {
                    newType = (ConstraintType)EditorGUILayout.EnumPopup(GUI.MakeLabel("Type"),
                                                                        refType,
                                                                        InspectorEditor.Skin.Popup,
                                                                        GUILayout.Width(EditorGUIUtility.labelWidth +
                                                                                        2.0f * 76.0f));
                }
            }

            EditorGUI.showMixedValue = false;

            // Avoiding change to Unknown when it wasn't possible
            // to handle undo/redo for that case.
            if (newType != refType && newType != ConstraintType.Unknown)
            {
                var performChange = constraints.All(c => c.Type == ConstraintType.Unknown) ||
                                    EditorUtility.DisplayDialog("Change constraint type",
                                                                "Any changes to parameters (compliance, damping etc.) and/or states of " +
                                                                $"any controller will be lost when the type changes to {newType}.\n\n" +
                                                                "Do you want to continue?",
                                                                "Yes",
                                                                "Cancel");
                if (performChange)
                {
                    var undoIndex = Undo.GetCurrentGroup();
                    foreach (var constraint in constraints)
                    {
                        if (newType == constraint.Type)
                        {
                            continue;
                        }

                        constraint.ChangeType(newType,
                                              createdObject =>
                        {
                            Undo.RegisterCreatedObjectUndo(createdObject, "ElementaryConstraint created.");
                        },
                                              destroyObject =>
                        {
                            Undo.DestroyObjectImmediate(destroyObject);
                        });
                    }
                    Undo.CollapseUndoOperations(undoIndex);
                }
            }

            return(!anyUnknownType);
        }