/// <summary> /// calculates height vert, and corner vert is based on height vert, then radius. /// </summary> /// <param name="attachTo"></param> public void CreateCapsuleColliderAlternate(Transform attachTo) { if (SelectedVertices.Count > 0) { for (int i = 0; i < SelectedVertices.Count; i++) {//converts selected vertices to local positions of object to attach collider to. SelectedVertices[i] = attachTo.InverseTransformPoint(SelectedVertices[i]); } Vector3 cornerVert = new Vector3(); Vector3 radiusVert = new Vector3(); Vector3 heightVert = new Vector3(); float maxDistance = 0; int cornerIndex = 0; for (int i = 0; i < SelectedVertices.Count; i++) { //Calculates height vertex as vertex furest from all the others. and corner vertex and vertex closest to the height vertex. float distance = 0; float minDistance = Mathf.Infinity; for (int j = 0; j < SelectedVertices.Count; j++) { if (i != j) { float vecDistance = Vector3.Distance(SelectedVertices[i], SelectedVertices[j]); distance += vecDistance; if (vecDistance < minDistance) { minDistance = vecDistance; cornerIndex = j; } } } if (distance > maxDistance) { maxDistance = distance; heightVert = SelectedVertices[i]; cornerVert = SelectedVertices[cornerIndex]; } } float radius = 0; for (int i = 0; i < SelectedVertices.Count; i++) { //calculates radius as closest vert distance that isn't height if (SelectedVertices[i] != cornerVert && SelectedVertices[i] != heightVert) { float distance = Vector3.Distance(SelectedVertices[i], cornerVert); if (distance > radius) { radius = distance; radiusVert = SelectedVertices[i]; } } } int direction; float dX = Mathf.Abs(heightVert.x - cornerVert.x); float dY = Mathf.Abs(heightVert.y - cornerVert.y); if (dX < 0.001F) { if (dY < 0.001F) { direction = 2; } else { direction = 1; } } else { direction = 0; } float maxHeight = Vector3.Distance(cornerVert, heightVert); Vector3 center = (heightVert + radiusVert) / 2; CapsuleCollider capsule = Undo.AddComponent <CapsuleCollider>(attachTo.gameObject); capsule.radius = Vector3.Distance(cornerVert, radiusVert) / 2; capsule.height = maxHeight + (capsule.radius * 2); capsule.center = center; capsule.direction = direction; capsule.isTrigger = IsTrigger; SelectedVertices.Clear(); Selection.activeGameObject = attachTo.gameObject; } }
string AddComponentForSuit() { string output = string.Empty; DefinedSuit suitDef = null; if (SuitRoot != null) { suitDef = SuitRoot.GetComponent <DefinedSuit>(); if (suitDef == null) { SuitRoot.AddComponent <DefinedSuit>(); } } if (suitDef != null) { suitDef.MySuit.AddChildObjects = AddChildObjects; suitDef.MySuit.AddExclusiveTriggerCollider = AddExclusiveTriggerCollider; suitDef.MySuit.SuitHolders = SuitHolders.ToList(); suitDef.MySuit.DefaultOptions = DefaultOptions.ToList(); suitDef.MySuit.SuitRoot = SuitRoot; } for (int i = 0; i < SuitHolders.Count; i++) { if (SuitHolders[i] != null) { Undo.RecordObject(SuitHolders[i], "Add Suit Node to Marked Objects"); output += "Processing " + SuitHolders[i].name + ""; GameObject targetGO = AddChildObjects ? SuitHolders[i].transform.FindChild(SuitHolders[i].name + childAppendName).gameObject : SuitHolders[i]; Collider col = null; //Check if it has one already SuitBodyCollider suit = targetGO.GetComponent <SuitBodyCollider>(); if (suit == null) { //Add one if it doesn't //suit = targetGO.AddComponent<SuitBodyCollider>(); - Not undo-able suit = Undo.AddComponent <SuitBodyCollider>(targetGO); if (AddExclusiveTriggerCollider) { col = AddColliderForSuit(suit); } if (suitDef != null) { suitDef.MySuit.SceneReferences[i] = suit; } output += "\t Adding Suit Body Collider to " + SuitHolders[i].name + ""; } output += "\t Adding " + DefaultOptions[i].ToString() + " " + SuitHolders[i].name + "\n"; //Add this region to it. suit.regionID = suit.regionID | DefaultOptions[i]; //Save the collider if we made one if (col != null) { suit.myCollider = col; } SceneReferences[i] = suit; //Don't let the user change anything until they've deleted these? //These functions aren't robust enough yet. CanChangeValues = false; } } output = "Creating SuitBodyCollider - Operation Finished\n\n" + output + "\n"; return(output); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { Type type = fieldInfo.FieldType; if (type.IsGenericType) { type = type.GenericTypeArguments.Single(); } if (type.HasElementType) { type = type.GetElementType(); } while (type != null && type.BaseType != typeof(InterfaceContainer)) { type = type.BaseType; } if (type?.BaseType != typeof(InterfaceContainer)) { throw new ArgumentException(); } type = type.GenericTypeArguments.Single(); using (new EditorGUI.PropertyScope(position, label, property)) { label.tooltip = EditorHelper.GetTooltipAttribute(fieldInfo)?.tooltip ?? string.Empty; position.height = EditorGUIUtility.singleLineHeight; SerializedObject serializedObject = property.serializedObject; SerializedProperty fieldProperty = property.FindPropertyRelative("field"); bool showChildren; int hashCode = property.propertyPath.GetHashCode(); ShowChildrenByObjectId.TryGetValue(hashCode, out showChildren); bool hasReference = fieldProperty.objectReferenceValue != null; bool isCircularReference = fieldProperty.objectReferenceValue == serializedObject.targetObject; Rect foldoutRect = position; if (hasReference && !isCircularReference) { foldoutRect.width = EditorGUI.IndentedRect(new Rect(Vector2.zero, Vector2.zero)).x; ShowChildrenByObjectId[hashCode] = EditorGUI.Foldout(foldoutRect, showChildren, GUIContent.none, true); } GUIContent buttonContent = new GUIContent( hasReference ? "-" : "+", $"{(hasReference ? "Remove" : "Add a new")} {type.Name} {(hasReference ? "from" : "to")} this game object."); float addButtonWidth; float removeButtonWidth; float buttonMaxWidth; GUI.skin.button.CalcMinMaxWidth(new GUIContent("+"), out addButtonWidth, out buttonMaxWidth); GUI.skin.button.CalcMinMaxWidth(new GUIContent("-"), out removeButtonWidth, out buttonMaxWidth); float buttonWidth = Mathf.Max(addButtonWidth, removeButtonWidth); using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope()) { Rect pickerRect = position; pickerRect.width -= buttonWidth + 2f * EditorGUIUtility.standardVerticalSpacing; EditorGUI.ObjectField(pickerRect, fieldProperty, type, label); if (changeCheckScope.changed) { serializedObject.ApplyModifiedProperties(); } } Rect buttonRect = position; buttonRect.x = buttonRect.width - 2f * EditorGUIUtility.standardVerticalSpacing; buttonRect.width = buttonWidth; if (GUI.Button(buttonRect, buttonContent)) { if (hasReference) { UnityEngine.Object reference = fieldProperty.objectReferenceValue; fieldProperty.objectReferenceValue = null; serializedObject.ApplyModifiedProperties(); Undo.DestroyObjectImmediate(reference); /* * Because we remove a component on the same game object the inspector is drawing currently * Unity will encounter the removed component and throw an exception trying to draw the * inspector for it. This instruction will basically tell Unity to skip the current GUI * loop iteration, preventing any errors. */ GUIUtility.ExitGUI(); return; } Rect creatorRect = new Rect { min = GUIUtility.GUIToScreenPoint(position.min + Vector2.right * EditorGUIUtility.labelWidth), max = GUIUtility.GUIToScreenPoint(buttonRect.max) }; TypePickerWindow.Show( creatorRect, type, selectedType => { fieldProperty.objectReferenceValue = Undo.AddComponent(Selection.activeGameObject, selectedType); InternalEditorUtility.SetIsInspectorExpanded(fieldProperty.objectReferenceValue, false); serializedObject.ApplyModifiedProperties(); ShowChildrenByObjectId[hashCode] = true; }); } if (!showChildren || !hasReference || isCircularReference) { return; } /* * Keep repainting this PropertyDrawer because a child is visible. This ensures the property fields * of the child are updated when an undo operation is performed. */ EditorUtility.SetDirty(serializedObject.targetObject); position.y += position.height; using (new EditorGUI.IndentLevelScope()) { SerializedObject fieldSerializedObject = new SerializedObject(fieldProperty.objectReferenceValue); SerializedProperty iteratedProperty = fieldSerializedObject.GetIterator(); iteratedProperty.NextVisible(true); while (iteratedProperty.NextVisible(false)) { using (new EditorGUI.PropertyScope(position, label, iteratedProperty)) using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope()) { float propertyHeight = EditorGUI.GetPropertyHeight(iteratedProperty); bool expandedChildren = EditorGUI.PropertyField( new Rect(position.x, position.y, position.width, propertyHeight), iteratedProperty, true); if (changeCheckScope.changed) { iteratedProperty.serializedObject.ApplyModifiedProperties(); } if (!expandedChildren) { break; } position.y += propertyHeight; } } } } }
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); } }; }
void AddReceiverComponent() { var receiver = Undo.AddComponent <SignalReceiver>(m_BoundGameObject); receiver.AddNewReaction(signalAsset); }
void _createAudioManager() { AudioManager am = character.GetComponent <AudioManager>(); if (!am) { am = Undo.AddComponent <AudioManager>(character); } WeaponAudio ms = character.GetComponent <WeaponAudio>(); if (!ms) { ms = Undo.AddComponent <WeaponAudio>(character); } // load default clips AudioClip grunt1 = Resources.Load <AudioClip>("Audio/grunt1"); AudioClip grunt2 = Resources.Load <AudioClip>("Audio/grunt2"); AudioClip grunt4 = Resources.Load <AudioClip>("Audio/grunt4"); AudioClip grunt5 = Resources.Load <AudioClip>("Audio/grunt5"); AudioClip punch1 = Resources.Load <AudioClip>("Audio/punch1"); AudioClip smack1 = Resources.Load <AudioClip>("Audio/smack1"); AudioClip smack2 = Resources.Load <AudioClip>("Audio/smack2"); AudioClip smack3 = Resources.Load <AudioClip>("Audio/smack3"); AudioClip block1 = Resources.Load <AudioClip>("Audio/block1"); if (!grunt1) { Debug.LogWarning("Unable to load clip: 'Audio/grunt1'"); } if (!grunt2) { Debug.LogWarning("Unable to load clip: 'Audio/grunt2'"); } if (!grunt4) { Debug.LogWarning("Unable to load clip: 'Audio/grunt4'"); } if (!grunt5) { Debug.LogWarning("Unable to load clip: 'Audio/grunt5'"); } if (!punch1) { Debug.LogWarning("Unable to load clip: 'Audio/punch1'"); } if (!smack1) { Debug.LogWarning("Unable to load clip: 'Audio/smack1'"); } if (!smack2) { Debug.LogWarning("Unable to load clip: 'Audio/smack2'"); } if (!smack3) { Debug.LogWarning("Unable to load clip: 'Audio/smack3'"); } if (!block1) { Debug.LogWarning("Unable to load clip: 'Audio/block1'"); } am.jumpSounds = new AudioClip[] { grunt1, grunt5 }; am.diveRollSounds = new AudioClip[] { grunt2 }; ms.attackSwingSounds = new AudioClip[] { grunt4, grunt5 }; ms.attackHitSounds = new AudioClip[] { punch1, smack1, smack2, smack3 }; ms.blockSounds = new AudioClip[] { block1 }; }
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); } } #if UNITY_2021_2_OR_NEWER CinemachineSceneToolUtility.RegisterTool(typeof(FoVTool)); CinemachineSceneToolUtility.RegisterTool(typeof(FarNearClipTool)); #endif }
static XRRig CreateXRRig(Transform parentOfNewGameObject, InputType inputType) { var xrCamera = Camera.main; // Don't use if the MainCamera is not part of the current stage being edited. if (xrCamera != null && !StageUtility.GetCurrentStageHandle().Contains(xrCamera.gameObject)) { xrCamera = null; } // If the existing MainCamera is already part of an XR Rig, // create a new camera instead of trying to reuse it. if (xrCamera != null && xrCamera.GetComponentInParent <XRRig>() != null) { xrCamera = null; } // If the existing MainCamera is selected, the hierarchy would be invalid // since the camera should be a child of the rig. if (xrCamera != null && xrCamera.transform == parentOfNewGameObject) { parentOfNewGameObject = parentOfNewGameObject.parent; } CreateInteractionManager(); var xrRigGO = CreateAndPlaceGameObject("XR Rig", parentOfNewGameObject, typeof(XRRig)); var cameraOffsetGO = ObjectFactory.CreateGameObject("Camera Offset"); Place(cameraOffsetGO, xrRigGO.transform); if (xrCamera == null) { var xrCameraGO = ObjectFactory.CreateGameObject("Main Camera", typeof(Camera), typeof(AudioListener), GetTrackedPoseDriverType(inputType)); xrCamera = xrCameraGO.GetComponent <Camera>(); } Undo.RecordObject(xrCamera, "Configure Camera"); xrCamera.tag = "MainCamera"; xrCamera.nearClipPlane = 0.01f; Place(xrCamera.gameObject, cameraOffsetGO.transform); switch (inputType) { case InputType.ActionBased: { var trackedPoseDriver = xrCamera.GetComponent <UnityEngine.InputSystem.XR.TrackedPoseDriver>(); if (trackedPoseDriver == null) { trackedPoseDriver = Undo.AddComponent <UnityEngine.InputSystem.XR.TrackedPoseDriver>(xrCamera.gameObject); } Undo.RecordObject(trackedPoseDriver, "Configure Tracked Pose Driver"); trackedPoseDriver.positionAction = new InputAction(null, InputActionType.Value, "<XRHMD>/centerEyePosition", null, null, "Vector3"); trackedPoseDriver.rotationAction = new InputAction(null, InputActionType.Value, "<XRHMD>/centerEyeRotation", null, null, "Quaternion"); break; } case InputType.DeviceBased: { var trackedPoseDriver = xrCamera.GetComponent <TrackedPoseDriver>(); if (trackedPoseDriver == null) { trackedPoseDriver = Undo.AddComponent <TrackedPoseDriver>(xrCamera.gameObject); } Undo.RecordObject(trackedPoseDriver, "Configure Tracked Pose Driver"); trackedPoseDriver.SetPoseSource(TrackedPoseDriver.DeviceType.GenericXRDevice, TrackedPoseDriver.TrackedPose.Center); break; } default: throw new InvalidEnumArgumentException(nameof(inputType), (int)inputType, typeof(InputType)); } var xrRig = xrRigGO.GetComponent <XRRig>(); Undo.RecordObject(xrRig, "Configure XR Rig"); xrRig.cameraFloorOffsetObject = cameraOffsetGO; xrRig.cameraGameObject = xrCamera.gameObject; return(xrRig); }
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 CinemachineNewVirtualCamera; 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 CinemachineNewVirtualCamera; if (vcam != null) { Component c = vcam.GetCinemachineComponent(stage); if (c != null && c.GetType() == type) { continue; } if (c != null) { Undo.DestroyObjectImmediate(c); vcam.InvalidateComponentCache(); } if (type != null) { Undo.AddComponent(vcam.gameObject, type); vcam.InvalidateComponentCache(); } } } }); m_PipelineSet.SetStageIsLocked(CinemachineCore.Stage.Body); for (int i = 0; i < targets.Length; ++i) { (targets[i] as CinemachineNewFreeLook).UpdateInputAxisProvider(); } #if UNITY_2021_2_OR_NEWER CinemachineSceneToolUtility.RegisterTool(typeof(FoVTool)); CinemachineSceneToolUtility.RegisterTool(typeof(FarNearClipTool)); CinemachineSceneToolUtility.RegisterTool(typeof(FollowOffsetTool)); #endif }
internal void OnInspectorGui(BGCurvePointI point, int index, BGCurveSettings settings) { var mode2D = point.Curve.Mode2D; //point transform if (point.Curve.PointsMode != BGCurve.PointsModeEnum.Inlined && point.PointTransform != null) { var referenceToPoint = BGCurveReferenceToPoint.GetReferenceToPoint(point); if (referenceToPoint == null) { point.PointTransform.gameObject.AddComponent <BGCurveReferenceToPoint>().Point = point; } } BGEditorUtility.HorizontalBox(() => { if (editorSelection != null) { editorSelection.InspectorSelectionRect(point); } BGEditorUtility.VerticalBox(() => { BGEditorUtility.SwapLabelWidth(60, () => { if (!settings.ShowPointPosition && !settings.ShowPointControlType) { BGEditorUtility.Horizontal(() => { //nothing to show- only label EditorGUILayout.LabelField("Point " + index); PointButtons(point, index, settings); }); BGEditorUtility.StartIndent(1); } else { //control type if (settings.ShowPointControlType) { BGEditorUtility.Horizontal(() => { point.ControlType = (BGCurvePoint.ControlTypeEnum)EditorGUILayout.EnumPopup("Point " + index, point.ControlType); PointButtons(point, index, settings); }); BGEditorUtility.StartIndent(1); } //position if (settings.ShowPointPosition) { if (!settings.ShowPointControlType) { BGEditorUtility.Horizontal(() => { PositionField("Point " + index, point, mode2D, index); PointButtons(point, index, settings); }); BGEditorUtility.StartIndent(1); } else { PositionField("Pos", point, mode2D, index); } } } }); // control positions if (point.ControlType != BGCurvePoint.ControlTypeEnum.Absent && settings.ShowPointControlPositions) { // 1st ControlField(point, mode2D, 1); // 2nd ControlField(point, mode2D, 2); } //transform if (settings.ShowTransformField) { BGEditorUtility.ComponentField("Transform", point.PointTransform, transform => { if (transform != null) { Undo.RecordObject(transform, "Object moved"); if (point.Curve.PointsMode != BGCurve.PointsModeEnum.Inlined) { Undo.AddComponent <BGCurveReferenceToPoint>(transform.gameObject).Point = point; } } if (point.PointTransform != null) { var referenceToPoint = BGCurveReferenceToPoint.GetReferenceToPoint(point); if (referenceToPoint != null) { Undo.DestroyObjectImmediate(referenceToPoint); } } point.PointTransform = transform; }); } //fields if (point.Curve.FieldsCount > 0) { ShowFields(point); } BGEditorUtility.EndIndent(1); }); }); }
public static T AddComponent <T>(GameObject gameObject) where T : Component { return(Undo.AddComponent <T>(gameObject)); }
public override void OnInspectorGUI() { EditorGUILayout.BeginHorizontal(); GUILayout.Label("Online Document"); if (GUILayout.Button("<color=blue>http://nyahoon.com/products/dynamic-shadow-projector/shadow-texture-renderer-component</color>", richTextStyle)) { Application.OpenURL("http://nyahoon.com/products/dynamic-shadow-projector/shadow-texture-renderer-component"); } EditorGUILayout.EndHorizontal(); bool isGUIEnabled = GUI.enabled; EditorGUILayout.PropertyField(serializedObject.FindProperty("m_shadowColor")); EditorGUILayout.IntPopup(serializedObject.FindProperty("m_textureWidth"), s_textureSizeDisplayOption, s_textureSizeOption); EditorGUILayout.IntPopup(serializedObject.FindProperty("m_textureHeight"), s_textureSizeDisplayOption, s_textureSizeOption); EditorGUILayout.PropertyField(serializedObject.FindProperty("m_multiSampling")); EditorGUILayout.PropertyField(serializedObject.FindProperty("m_superSampling")); SerializedProperty prop = serializedObject.FindProperty("m_blurLevel"); EditorGUILayout.IntPopup(prop, s_blurLevelDisplayOption, s_blurLevelOption); ++EditorGUI.indentLevel; GUI.enabled = isGUIEnabled && 0 < prop.intValue; ShadowTextureRenderer shadowRenderer = target as ShadowTextureRenderer; EditorGUILayout.Slider(serializedObject.FindProperty("m_blurSize"), 1.0f, shadowRenderer.blurFilter == ShadowTextureRenderer.BlurFilter.Uniform ? 6.0f : 4.0f); GUI.enabled = isGUIEnabled; --EditorGUI.indentLevel; prop = serializedObject.FindProperty("m_mipLevel"); EditorGUILayout.PropertyField(prop); ++EditorGUI.indentLevel; GUI.enabled = isGUIEnabled && 0 < prop.intValue; SerializedProperty fastBlur = serializedObject.FindProperty("m_singlePassMipmapBlur"); EditorGUILayout.PropertyField(fastBlur); float maxBlurSize; if (fastBlur.boolValue) { maxBlurSize = 1.0f; } else { maxBlurSize = shadowRenderer.blurFilter == ShadowTextureRenderer.BlurFilter.Uniform ? 3.0f : 2.0f; } EditorGUILayout.Slider(serializedObject.FindProperty("m_mipmapBlurSize"), 0.0f, maxBlurSize); if (shadowRenderer.GetComponent <MipmappedShadowFallback>() == null) { EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add Fallback Component")) { Undo.AddComponent <MipmappedShadowFallback>(shadowRenderer.gameObject); } EditorGUILayout.EndHorizontal(); GUI.enabled = isGUIEnabled; --EditorGUI.indentLevel; } else if (prop.intValue == 0) { GUI.enabled = isGUIEnabled; --EditorGUI.indentLevel; EditorGUILayout.BeginHorizontal(); GUILayout.TextArea("<color=red>Still has Mipmap Fallback Component!</color>", richTextStyle); if (GUILayout.Button("Remove the Component")) { Undo.DestroyObjectImmediate(shadowRenderer.GetComponent <MipmappedShadowFallback>()); } EditorGUILayout.EndHorizontal(); } else { GUI.enabled = isGUIEnabled; --EditorGUI.indentLevel; } prop = serializedObject.FindProperty("m_testViewClip"); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Don't update while out of view"); prop.boolValue = EditorGUILayout.Toggle(prop.boolValue); EditorGUILayout.EndHorizontal(); ++EditorGUI.indentLevel; GUI.enabled = isGUIEnabled && prop.boolValue; EditorGUILayout.PropertyField(serializedObject.FindProperty("m_camerasForViewClipTest"), true); GUI.enabled = isGUIEnabled; --EditorGUI.indentLevel; s_showAdvancedOptions = GUILayout.Toggle(s_showAdvancedOptions, "Show Advanced Options"); if (s_showAdvancedOptions) { ++EditorGUI.indentLevel; EditorGUILayout.PropertyField(serializedObject.FindProperty("m_blurFilter")); prop = serializedObject.FindProperty("m_mipmapFalloff"); EditorGUILayout.PropertyField(prop); if (prop.intValue == (int)ShadowTextureRenderer.MipmapFalloff.Custom) { prop = serializedObject.FindProperty("m_customMipmapFalloff"); if (shadowRenderer.customMipmapFalloff != null && shadowRenderer.customMipmapFalloff.Length != prop.arraySize) { serializedObject.Update(); prop = serializedObject.FindProperty("m_customMipmapFalloff"); } EditorGUILayout.PropertyField(prop, true); } float near = EditorGUILayout.FloatField("Near Clip Plane", shadowRenderer.cameraNearClipPlane); if (m_cameraSerializedObject == null) { m_camera = shadowRenderer.GetComponent <Camera>(); m_cameraSerializedObject = new SerializedObject(shadowRenderer.GetComponent <Camera>()); } if (near != shadowRenderer.cameraNearClipPlane) { Undo.RecordObject(m_camera, "Inspector"); shadowRenderer.cameraNearClipPlane = near; } bool bShowCamera = (m_camera.hideFlags & HideFlags.HideInInspector) == 0; bool newValue = EditorGUILayout.Toggle("Show Camera in Inspector", bShowCamera); if (bShowCamera != newValue) { if (newValue) { m_camera.hideFlags &= ~HideFlags.HideInInspector; } else { m_camera.hideFlags |= HideFlags.HideInInspector; } } EditorGUILayout.PropertyField(serializedObject.FindProperty("m_blurShader")); EditorGUILayout.PropertyField(serializedObject.FindProperty("m_downsampleShader")); EditorGUILayout.PropertyField(serializedObject.FindProperty("m_copyMipmapShader")); EditorGUILayout.PropertyField(serializedObject.FindProperty("m_preferredTextureFormats"), true); --EditorGUI.indentLevel; } serializedObject.ApplyModifiedProperties(); }
private bool ShowMRTKButton() { if (!canvas.rootCanvas) { return(false); } bool isMRTKCanvas = canvas.GetComponent <CanvasUtility>() != null; if (isMRTKCanvas) { if (GUILayout.Button(RemoveMRTKCanvas)) { EditorApplication.delayCall += () => { DestroyImmediate(canvas.GetComponent <NearInteractionTouchableUnityUI>()); DestroyImmediate(canvas.GetComponent <CanvasUtility>()); }; isMRTKCanvas = false; } if (canvas.renderMode == RenderMode.WorldSpace && canvas.worldCamera != null && !Application.isPlaying) { EditorGUILayout.HelpBox("World Space Canvas should not have a camera set to work properly with MRTK. At runtime, it'll get its camera set automatically.", MessageType.Error); if (GUILayout.Button("Clear World Camera")) { Undo.RecordObject(canvas, "Clear World Camera"); canvas.worldCamera = null; } } if (canvas.renderMode != RenderMode.WorldSpace) { EditorGUILayout.HelpBox($"Canvas must be set to World Space to work properly with MRTK.", MessageType.Warning); if (GUILayout.Button("Update Render Mode to World Space")) { Undo.RecordObject(target, "Change Render Mode"); canvas.renderMode = RenderMode.WorldSpace; } } if (canvas.GetComponentInChildren <NearInteractionTouchableUnityUI>() == null) { EditorGUILayout.HelpBox($"Canvas does not contain any {typeof(NearInteractionTouchableUnityUI).Name} components for supporting near interaction.", MessageType.Warning); if (GUILayout.Button($"Add {typeof(NearInteractionTouchableUnityUI).Name}")) { Undo.AddComponent <NearInteractionTouchableUnityUI>(canvas.gameObject); } } } else { if (GUILayout.Button(MakeMRTKCanvas)) { if (canvas.GetComponent <GraphicRaycaster>() == null) { Undo.AddComponent <GraphicRaycaster>(canvas.gameObject); } if (canvas.GetComponent <CanvasUtility>() == null) { Undo.AddComponent <CanvasUtility>(canvas.gameObject); } canvas.renderMode = RenderMode.WorldSpace; canvas.worldCamera = null; isMRTKCanvas = true; } } return(isMRTKCanvas); }
/// <summary> /// calculates corner first, then height & radius. /// </summary> /// <param name="attachTo"></param> public void CreateCapsuleCollider(Transform attachTo) { if (SelectedVertices.Count > 0) { for (int i = 0; i < SelectedVertices.Count; i++) {//converts selected vertices to local positions of object to attach collider to. SelectedVertices[i] = attachTo.InverseTransformPoint(SelectedVertices[i]); } Vector3 cornerVert = new Vector3(); Vector3 radiusVert = new Vector3(); Vector3 heightVert = new Vector3(); float minDistance = Mathf.Infinity; for (int i = 0; i < SelectedVertices.Count; i++) { //Calculates corner vertex. float cornerDist = 0F; for (int j = 0; j < SelectedVertices.Count; j++) { if (i != j) { cornerDist += Vector3.Distance(SelectedVertices[i], SelectedVertices[j]); } } if (cornerDist < minDistance) { cornerVert = SelectedVertices[i]; minDistance = cornerDist; } } float radius = Mathf.Infinity; float height = 0; for (int i = 0; i < SelectedVertices.Count; i++) { //calculates height and radius vertex / distances. if (SelectedVertices[i] != cornerVert) { float distance = Vector3.Distance(SelectedVertices[i], cornerVert); if (distance < radius) { radius = distance; radiusVert = SelectedVertices[i]; } if (distance > height) { height = distance; heightVert = SelectedVertices[i]; } } } int direction; float dX = Mathf.Abs(heightVert.x - cornerVert.x); float dY = Mathf.Abs(heightVert.y - cornerVert.y); if (dX < 0.001F) { if (dY < 0.001F) { direction = 2; } else { direction = 1; } } else { direction = 0; } float maxHeight = Vector3.Distance(cornerVert, heightVert); Vector3 center = (heightVert + radiusVert) / 2; CapsuleCollider capsule = Undo.AddComponent <CapsuleCollider>(attachTo.gameObject); capsule.radius = Vector3.Distance(cornerVert, radiusVert) / 2; capsule.height = maxHeight + (capsule.radius * 2); capsule.center = center; capsule.direction = direction; capsule.isTrigger = IsTrigger; SelectedVertices.Clear(); Selection.activeGameObject = attachTo.gameObject; } }
private void DrawObservedComponentsList() { GUILayout.Space(5); SerializedProperty listProperty = this.serializedObject.FindProperty("ObservedComponents"); if (listProperty == null) { return; } float containerElementHeight = 22; float containerHeight = listProperty.arraySize * containerElementHeight; bool isOpen = PhotonGUI.ContainerHeaderFoldout("Observed Components (" + this.GetObservedComponentsCount() + ")", this.serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue); this.serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue = isOpen; if (isOpen == false) { containerHeight = 0; } //Texture2D statsIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonViewStats.png", typeof( Texture2D ) ) as Texture2D; Rect containerRect = PhotonGUI.ContainerBody(containerHeight); bool wasObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (isOpen == true) { for (int i = 0; i < listProperty.arraySize; ++i) { Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + containerElementHeight * i, containerRect.width, containerElementHeight); { Rect texturePosition = new Rect(elementRect.xMin + 6, elementRect.yMin + elementRect.height / 2f - 1, 9, 5); ReorderableListResources.DrawTexture(texturePosition, ReorderableListResources.texGrabHandle); Rect propertyPosition = new Rect(elementRect.xMin + 20, elementRect.yMin + 3, elementRect.width - 45, 16); // keep track of old type to catch when a new type is observed Type _oldType = listProperty.GetArrayElementAtIndex(i).objectReferenceValue != null?listProperty.GetArrayElementAtIndex(i).objectReferenceValue.GetType() : null; EditorGUI.PropertyField(propertyPosition, listProperty.GetArrayElementAtIndex(i), new GUIContent()); // new type, could be different from old type Type _newType = listProperty.GetArrayElementAtIndex(i).objectReferenceValue != null?listProperty.GetArrayElementAtIndex(i).objectReferenceValue.GetType() : null; // the user dropped a Transform, we must change it by adding a PhotonTransformView and observe that instead if (_oldType != _newType) { if (_newType == typeof(PhotonView)) { listProperty.GetArrayElementAtIndex(i).objectReferenceValue = null; Debug.LogError("PhotonView Detected you dropped a PhotonView, this is not allowed. \n It's been removed from observed field."); } else if (_newType == typeof(Transform)) { // try to get an existing PhotonTransformView ( we don't want any duplicates...) PhotonTransformView _ptv = this.m_Target.gameObject.GetComponent <PhotonTransformView>(); if (_ptv == null) { // no ptv yet, we create one and enable position and rotation, no scaling, as it's too rarely needed to take bandwidth for nothing _ptv = Undo.AddComponent <PhotonTransformView>(this.m_Target.gameObject); } // switch observe from transform to _ptv listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _ptv; Debug.Log("PhotonView has detected you dropped a Transform. Instead it's better to observe a PhotonTransformView for better control and performances"); } else if (_newType == typeof(Rigidbody)) { Rigidbody _rb = listProperty.GetArrayElementAtIndex(i).objectReferenceValue as Rigidbody; // try to get an existing PhotonRigidbodyView ( we don't want any duplicates...) PhotonRigidbodyView _prbv = _rb.gameObject.GetComponent <PhotonRigidbodyView>(); if (_prbv == null) { // no _prbv yet, we create one _prbv = Undo.AddComponent <PhotonRigidbodyView>(_rb.gameObject); } // switch observe from transform to _prbv listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _prbv; Debug.Log("PhotonView has detected you dropped a RigidBody. Instead it's better to observe a PhotonRigidbodyView for better control and performances"); } else if (_newType == typeof(Rigidbody2D)) { // try to get an existing PhotonRigidbody2DView ( we don't want any duplicates...) PhotonRigidbody2DView _prb2dv = this.m_Target.gameObject.GetComponent <PhotonRigidbody2DView>(); if (_prb2dv == null) { // no _prb2dv yet, we create one _prb2dv = Undo.AddComponent <PhotonRigidbody2DView>(this.m_Target.gameObject); } // switch observe from transform to _prb2dv listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _prb2dv; Debug.Log("PhotonView has detected you dropped a Rigidbody2D. Instead it's better to observe a PhotonRigidbody2DView for better control and performances"); } else if (_newType == typeof(Animator)) { // try to get an existing PhotonAnimatorView ( we don't want any duplicates...) PhotonAnimatorView _pav = this.m_Target.gameObject.GetComponent <PhotonAnimatorView>(); if (_pav == null) { // no _pav yet, we create one _pav = Undo.AddComponent <PhotonAnimatorView>(this.m_Target.gameObject); } // switch observe from transform to _prb2dv listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _pav; Debug.Log("PhotonView has detected you dropped a Animator, so we switched to PhotonAnimatorView so that you can serialized the Animator variables"); } else if (!typeof(IPunObservable).IsAssignableFrom(_newType)) { bool _ignore = false; #if PLAYMAKER _ignore = _newType == typeof(PlayMakerFSM);// Photon Integration for PlayMaker will swap at runtime to a proxy using iPunObservable. #endif if (_newType == null || _newType == typeof(Rigidbody) || _newType == typeof(Rigidbody2D)) { _ignore = true; } if (!_ignore) { listProperty.GetArrayElementAtIndex(i).objectReferenceValue = null; Debug.LogError("PhotonView Detected you dropped a Component missing IPunObservable Interface,\n You dropped a <" + _newType + "> instead. It's been removed from observed field."); } } } //Debug.Log( listProperty.GetArrayElementAtIndex( i ).objectReferenceValue.GetType() ); //Rect statsPosition = new Rect( propertyPosition.xMax + 7, propertyPosition.yMin, statsIcon.width, statsIcon.height ); //ReorderableListResources.DrawTexture( statsPosition, statsIcon ); Rect removeButtonRect = new Rect(elementRect.xMax - PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, elementRect.yMin + 2, PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, PhotonGUI.DefaultRemoveButtonStyle.fixedHeight); GUI.enabled = listProperty.arraySize > 1; if (GUI.Button(removeButtonRect, new GUIContent(ReorderableListResources.texRemoveButton), PhotonGUI.DefaultRemoveButtonStyle)) { listProperty.DeleteArrayElementAtIndex(i); } GUI.enabled = true; if (i < listProperty.arraySize - 1) { texturePosition = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1); PhotonGUI.DrawSplitter(texturePosition); } } } } if (PhotonGUI.AddButton()) { listProperty.InsertArrayElementAtIndex(Mathf.Max(0, listProperty.arraySize - 1)); } this.serializedObject.ApplyModifiedProperties(); bool isObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (wasObservedComponentsEmpty == true && isObservedComponentsEmpty == false && this.m_Target.Synchronization == ViewSynchronization.Off) { Undo.RecordObject(this.m_Target, "Change PhotonView"); this.m_Target.Synchronization = ViewSynchronization.UnreliableOnChange; this.serializedObject.Update(); } if (wasObservedComponentsEmpty == false && isObservedComponentsEmpty == true) { Undo.RecordObject(this.m_Target, "Change PhotonView"); this.m_Target.Synchronization = ViewSynchronization.Off; this.serializedObject.Update(); } }
//create rope void Create() { if (!chainObject.GetComponent <Collider2D>()) { helpText = "Chain Object Doesn't Have Collider2D Attached"; return; } if (!chainObject.GetComponent <HingeJoint2D>()) { helpText = "Chain Object Doesn't Have HingeJoint2D Attached"; return; } //if rope width is 0, that means that user hadn't set rope width, in that case we make width same as chainObject's renderer size if (ropeWidth <= 0.0f) { ropeWidth = chainObject.GetComponent <Renderer>().bounds.size.x; } //if pointA has 3D collider attached, remove it var colA = pointA.GetComponent <Collider>(); if (colA) { Undo.DestroyObjectImmediate(colA); } //if connectToA is set to true and pointA doesn't have DistanceJoint2D component yet, add it if (connectToA) { var jointA = pointA.GetComponent <DistanceJoint2D>(); if (!jointA || (jointA && jointA.connectedBody)) { Undo.AddComponent <DistanceJoint2D>(pointA.gameObject); //register undo } } //if pointB has 3D collider attached, remove it var colB = pointB.GetComponent <Collider>(); if (colB) { Undo.DestroyObjectImmediate(colB); } //if connectToB is set to true and pointB doesn't have DistanceJoint2D component yet, add it if (connectToB) { var jointB = pointB.GetComponent <DistanceJoint2D>(); if (!jointB || (jointB && jointB.connectedBody)) { Undo.AddComponent <DistanceJoint2D>(pointB.gameObject); //register undo } } //calculate how many chains is needed from pointA to pointB var chainCount = (int)(Vector3.Distance(pointA.position, pointB.position) / (chainObject.GetComponent <Renderer>().bounds.extents.x * 1.9f)); if (chainCount < 2) { helpText = "Distance between PointA & PointB is very small"; if (pointsHolder) { Debug.LogWarning("Distance from " + pointA.name + " (PointA) to " + pointB.name + " (PointB) is very small, increase distance"); } return; } //create "Chains Holder" object, used to make chains children of that object chainsHolder = new GameObject("Chains Holder"); Undo.RegisterCreatedObjectUndo(chainsHolder, "Create Rope"); //register undo //create rope Rope2D rope = new Rope2D(); rope.CreateRope(chainsHolder, chainObject, pointA, pointB, lockFirstChain, lockLastChain, connectToA, connectToB, hideEndChains, useLineRenderer, ropeMat, ropeWidth, ropeLength); }
/// <summary> /// Context Click selection. Here you'll need to register your own using a string identifier /// </summary> public void MenuNodeContextCallback(object obj) { Node node = Undo.AddComponent(nodeCanvas.contextContainer.gameObject, (Type)obj) as Node; node.Init(nodeCanvas, mousePos - nodeCanvas.scrollOffset); }
public override void OnInspectorGUI() { #if !OBSOLETE serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(actionAsset); if (EditorGUI.EndChangeCheck()) { InputActionAsset actions = actionAsset.objectReferenceValue as InputActionAsset; serializedObject.ApplyModifiedProperties(); PopulateActions(); serializedObject.Update(); if (actions != previousAsset) { ReassignActions(); previousAsset = actions; } } DoCreateActions(); EditorGUILayout.PropertyField(autoEnableInput); EditorGUILayout.PropertyField(autoDisableInput); EditorGUILayout.Space(); actionList.DoLayoutList(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Auto Assign")) { bool allNull = true; for (int i = 0; i < actions.arraySize; i++) { if (actions.GetArrayElementAtIndex(i).FindPropertyRelative("action").objectReferenceValue != null) { allNull = false; break; } } if (allNull || (!allNull && EditorUtility.DisplayDialog("Notice", "Your assigned input actions will be overwritten. Are you sure you want to do this?", "Yes", "No"))) { ReassignActions(); } } EditorGUILayout.EndHorizontal(); serializedObject.ApplyModifiedProperties(); #else if (GUILayout.Button("Replace with Gold Player Input")) { GameObject go = ((GoldPlayerInputSystem)target).gameObject; Undo.DestroyObjectImmediate(go.GetComponent <GoldPlayerInputSystem>()); Undo.AddComponent <GoldPlayerInput>(go); } #endif }
public static GameObject BoneCreationMode(Vector3 mousePos) { bool isSplineBone = false; if (Selection.activeGameObject == null) { if (Puppet2D_Editor.currentActiveBone) { Selection.activeGameObject = Puppet2D_Editor.currentActiveBone; } } if (Selection.activeGameObject) { if (Selection.activeGameObject.GetComponent <Puppet2D_HiddenBone>()) { Selection.activeGameObject = Selection.activeGameObject.transform.parent.gameObject; } if (Selection.activeGameObject.GetComponent <SpriteRenderer>()) { if (Selection.activeGameObject.GetComponent <SpriteRenderer>().sprite) { if (Selection.activeGameObject.GetComponent <SpriteRenderer>().sprite.name.Contains("Bone")) { // MAKE SURE SELECTION IS NOT AN IK OR PARENT Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType <Puppet2D_GlobalControl> (); for (int i = 0; i < globalCtrlScripts.Length; i++) { foreach (Puppet2D_IKHandle Ik in globalCtrlScripts[i]._Ikhandles) { if ((Ik.topJointTransform == Selection.activeGameObject.transform) || (Ik.bottomJointTransform == Selection.activeGameObject.transform) || (Ik.middleJointTransform == Selection.activeGameObject.transform)) { Debug.LogWarning("Cannot parent bone, as this one has an IK handle"); Selection.activeGameObject = null; return(null); } } foreach (Puppet2D_SplineControl splineCtrl in globalCtrlScripts[i]._SplineControls) { foreach (GameObject bone in splineCtrl.bones) { if (bone == Selection.activeGameObject) { isSplineBone = true; } } } } } else { return(null); } } else { return(null); } } else { return(null); } } GameObject newBone = new GameObject(GetUniqueBoneName("bone")); Undo.RegisterCreatedObjectUndo(newBone, "Created newBone"); newBone.transform.position = mousePos; newBone.transform.position = new Vector3(newBone.transform.position.x, newBone.transform.position.y, 0); if (Selection.activeGameObject) { newBone.transform.parent = Selection.activeGameObject.transform; GameObject newInvisibleBone = new GameObject(GetUniqueBoneName("hiddenBone")); Undo.RegisterCreatedObjectUndo(newInvisibleBone, "Created new invisible Bone"); SpriteRenderer spriteRendererInvisbile = newInvisibleBone.AddComponent <SpriteRenderer>(); newInvisibleBone.transform.position = new Vector3(10000, 10000, 10000); spriteRendererInvisbile.sortingLayerName = Puppet2D_Editor._boneSortingLayer; spriteRendererInvisbile.sprite = Puppet2D_Editor.boneHiddenSprite; newInvisibleBone.transform.parent = Selection.activeGameObject.transform; Undo.AddComponent(newInvisibleBone, typeof(Puppet2D_HiddenBone)); Puppet2D_HiddenBone hiddenBoneComp = newInvisibleBone.GetComponent <Puppet2D_HiddenBone>(); hiddenBoneComp.boneToAimAt = newBone.transform; hiddenBoneComp.Refresh(); } SpriteRenderer spriteRenderer = newBone.AddComponent <SpriteRenderer>(); spriteRenderer.sortingLayerName = Puppet2D_Editor._boneSortingLayer; if (isSplineBone) { newBone.transform.parent = null; } sortOutBoneHierachy(newBone); if (isSplineBone) { newBone.transform.parent = Selection.activeGameObject.transform; } Selection.activeGameObject = newBone; Puppet2D_Editor.currentActiveBone = newBone; return(newBone); }
// ================================================================================ Inspector public override void OnInspectorGui() { var settings = BGPrivateField.GetSettings(Curve); BGEditorUtility.HelpBox("Curve UI is disabled in settings. All handles are disabled too.", MessageType.Warning, !settings.ShowCurve); // Custom fields var warning = ""; BGEditorUtility.Assign(ref customUi, () => new BGTableView("Custom fields", new[] { "#", "Name", "Type", "?", "Delete" }, new[] { 5, 40, 40, 5, 10 }, () => { //add row customUi.NextColumn(rect => EditorGUI.LabelField(rect, "Name"), 12); customUi.NextColumn(rect => newFieldName = EditorGUI.TextField(rect, newFieldName), 28); customUi.NextColumn(rect => BGEditorUtility.PopupField(rect, newFieldType, @enum => newFieldType = (BGCurvePointField.TypeEnum)@enum), 50); customUi.NextColumn(rect => { if (!GUI.Button(rect, BGBinaryResources.BGAdd123)) { return; } if (NameHasError(Curve, newFieldName)) { return; } BGPrivateField.Invoke(Curve, BGCurve.MethodAddField, newFieldName, newFieldType, (Func <BGCurvePointField>)(() => Undo.AddComponent <BGCurvePointField>(Curve.gameObject))); GUIUtility.hotControl = 0; GUIUtility.ExitGUI(); }, 10); customUi.NextRow(); if (customFields == null || customFields.Length == 0) { customUi.NextRow("Name should be 16 chars max, starts with a letter and contain English chars and numbers only."); } else { //header customUi.DrawHeaders(); //fields var quaternionWithHandlesCount = 0; BGEditorUtility.ChangeCheck(() => { foreach (var customField in customFields) { if (customField.Field.Type == BGCurvePointField.TypeEnum.Quaternion && BGPrivateField.GetHandlesType(customField.Field) != 0) { quaternionWithHandlesCount++; } customField.Ui(customUi); } }, SceneView.RepaintAll); if (quaternionWithHandlesCount > 1) { warning = "You have more than one Quaternion field with Handles enabled. Only first field will be shown in Scene View"; } //footer customUi.NextRow("?- Show in Points Menu/Scene View"); } })); // System fields BGEditorUtility.Assign(ref systemUi, () => new BGTableView("System fields", new[] { "Name", "Value" }, new[] { LabelWidth, 100 - LabelWidth }, () => { BGEditorUtility.ChangeCheck(() => { foreach (var field in systemFields) { field.Ui(systemUi); } }, SceneView.RepaintAll); })); BGEditorUtility.Assign(ref systemFields, () => new[] { (SystemField) new SystemFieldPosition(settings), new SystemFieldControls(settings), new SystemFieldControlsType(settings), new SystemFieldTransform(settings), }); var fields = Curve.Fields; var hasFields = fields != null && fields.Length > 0; if (hasFields && (customFields == null || customFields.Length != fields.Length) || !hasFields && customFields != null && customFields.Length != fields.Length) { customFields = new PointField[fields.Length]; for (var i = 0; i < fields.Length; i++) { customFields[i] = new PointField(fields[i], i, BGBinaryResources.BGDelete123); } } //warnings BGEditorUtility.HelpBox("All handles for positions are disabled.", MessageType.Warning, settings.HandlesSettings.Disabled); BGEditorUtility.HelpBox("All handles for controls are disabled.", MessageType.Warning, settings.ControlHandlesSettings.Disabled); //====================== Custom fields customUi.OnGui(); //warnings BGEditorUtility.HelpBox(warning, MessageType.Warning, warning.Length > 0); //====================== System fields systemUi.OnGui(); GUILayout.Space(4); }
private void AllRootCanvases() { bool isMrtkCanvas = ShowMRTKButton(); var graphics = GetGraphicsWhichRequireScaleMeshEffect(targets); if (graphics.Count() != 0) { EditorGUILayout.HelpBox($"Canvas contains {graphics.Count()} {typeof(Graphic).Name}(s) which require a {typeof(ScaleMeshEffect).Name} to work with the {StandardShaderUtility.MrtkStandardShaderName} shader.", UnityEditor.MessageType.Warning); if (GUILayout.Button($"Add {typeof(ScaleMeshEffect).Name}(s)")) { foreach (var graphic in graphics) { Undo.AddComponent <ScaleMeshEffect>(graphic.gameObject); } } } EditorGUILayout.Space(); if (PlayerSettings.virtualRealitySupported && (m_RenderMode.enumValueIndex == (int)RenderMode.ScreenSpaceOverlay)) { EditorGUILayout.HelpBox("Using a render mode of ScreenSpaceOverlay while VR is enabled will cause the Canvas to continue to incur a rendering cost, even though the Canvas will not be visible in VR.", MessageType.Warning); } if (!isMrtkCanvas) { EditorGUILayout.PropertyField(m_RenderMode); } m_OverlayMode.target = m_RenderMode.intValue == 0; m_CameraMode.target = m_RenderMode.intValue == 1; m_WorldMode.target = m_RenderMode.intValue == 2; EditorGUI.indentLevel++; if (EditorGUILayout.BeginFadeGroup(m_OverlayMode.faded)) { EditorGUILayout.PropertyField(m_PixelPerfect); EditorGUILayout.PropertyField(m_SortingOrder, Styles.sortingOrder); GUIContent[] displayNames = (GUIContent[])getDisplayNames.Invoke(null, new object[] { }); EditorGUILayout.IntPopup(m_TargetDisplay, displayNames, (int[])getDisplayIndices.Invoke(null, new object[] { }), Styles.targetDisplay); } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(m_CameraMode.faded)) { EditorGUILayout.PropertyField(m_PixelPerfect); EditorGUILayout.PropertyField(m_Camera, Styles.renderCamera); if (m_Camera.objectReferenceValue == null) { EditorGUILayout.HelpBox("A Screen Space Canvas with no specified camera acts like an Overlay Canvas.", MessageType.Warning); } if (m_Camera.objectReferenceValue != null) { EditorGUILayout.PropertyField(m_PlaneDistance); } EditorGUILayout.Space(); if (m_Camera.objectReferenceValue != null) { sortingLayerField.Invoke(null, new object[] { Styles.m_SortingLayerStyle, m_SortingLayerID, EditorStyles.popup, EditorStyles.label }); } EditorGUILayout.PropertyField(m_SortingOrder, Styles.m_SortingOrderStyle); } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(m_WorldMode.faded)) { if (!isMrtkCanvas) { EditorGUILayout.PropertyField(m_Camera, Styles.eventCamera); if (m_Camera.objectReferenceValue == null) { EditorGUILayout.HelpBox("A World Space Canvas with no specified Event Camera may not register UI events correctly.", MessageType.Warning); } EditorGUILayout.Space(); } sortingLayerField.Invoke(null, new object[] { Styles.m_SortingLayerStyle, m_SortingLayerID, EditorStyles.popup }); EditorGUILayout.PropertyField(m_SortingOrder, Styles.m_SortingOrderStyle); } EditorGUILayout.EndFadeGroup(); EditorGUI.indentLevel--; }
private static void RunBehaviourSetup(UdonSharpBehaviour behaviour, bool withUndo) { UdonBehaviour backingBehaviour = GetBackingUdonBehaviour(behaviour); // Handle components pasted across different behaviours if (backingBehaviour && backingBehaviour.gameObject != behaviour.gameObject) { backingBehaviour = null; } // Handle pasting components on the same behaviour, assumes pasted components are always the last in the list. if (backingBehaviour) { int refCount = 0; UdonSharpBehaviour[] behaviours = backingBehaviour.GetComponents <UdonSharpBehaviour>(); foreach (UdonSharpBehaviour udonSharpBehaviour in behaviours) { if (GetBackingUdonBehaviour(udonSharpBehaviour) == backingBehaviour) { refCount++; } } if (refCount > 1 && behaviour == behaviours.Last()) { backingBehaviour = null; } } bool isPartOfPrefabInstance = PrefabUtility.IsPartOfPrefabInstance(behaviour) && PrefabUtility.GetCorrespondingObjectFromSource(behaviour) != behaviour; if (backingBehaviour == null) { if (isPartOfPrefabInstance) { UdonSharpUtils.LogWarning("Cannot setup behaviour on prefab instance, original prefab asset needs setup"); return; } SetIgnoreEvents(true); try { backingBehaviour = withUndo ? Undo.AddComponent <UdonBehaviour>(behaviour.gameObject) : behaviour.gameObject.AddComponent <UdonBehaviour>(); #pragma warning disable CS0618 // Type or member is obsolete backingBehaviour.SynchronizePosition = false; backingBehaviour.AllowCollisionOwnershipTransfer = false; #pragma warning restore CS0618 // Type or member is obsolete MoveComponentRelativeToComponent(backingBehaviour, behaviour, false); SetBackingUdonBehaviour(behaviour, backingBehaviour); SetBehaviourVersion(backingBehaviour, UdonSharpBehaviourVersion.CurrentVersion); SetSceneBehaviourUpgraded(backingBehaviour); // UdonSharpUtils.Log($"Created behaviour {backingBehaviour}", behaviour); } finally { SetIgnoreEvents(false); } _proxyBehaviourLookup.Add(backingBehaviour, behaviour); UdonSharpUtils.SetDirty(behaviour); UdonSharpUtils.SetDirty(backingBehaviour); } // Handle U# behaviours that have been added to a prefab via Added Component > Apply To Prefab, but have not had their backing behaviour added // if (isPartOfPrefabInstance && // backingBehaviour != null && // !PrefabUtility.IsPartOfPrefabInstance(backingBehaviour)) // { // PropertyModification[] modifications = PrefabUtility.GetPropertyModifications(behaviour); // // if (modifications != null) // { // // } // } UdonSharpProgramAsset programAsset = GetUdonSharpProgramAsset(behaviour); if (backingBehaviour.programSource == null) { backingBehaviour.programSource = programAsset; if (backingBehaviour.programSource == null) { UdonSharpUtils.LogError($"Unable to find valid U# program asset associated with script '{behaviour}'", behaviour); } UdonSharpUtils.SetDirty(backingBehaviour); } if (_serializedProgramAssetField.GetValue(backingBehaviour) == null) { SerializedObject componentAsset = new SerializedObject(backingBehaviour); SerializedProperty serializedProgramAssetProperty = componentAsset.FindProperty("serializedProgramAsset"); serializedProgramAssetProperty.objectReferenceValue = programAsset.SerializedProgramAsset; if (withUndo) { componentAsset.ApplyModifiedProperties(); } else { componentAsset.ApplyModifiedPropertiesWithoutUndo(); } } if (backingBehaviour.enabled != behaviour.enabled) { if (withUndo) { Undo.RecordObject(backingBehaviour, "Enabled change"); } backingBehaviour.enabled = behaviour.enabled; if (!withUndo) { UdonSharpUtils.SetDirty(backingBehaviour); } } #if UDONSHARP_DEBUG backingBehaviour.hideFlags &= ~HideFlags.HideInInspector; #else backingBehaviour.hideFlags |= HideFlags.HideInInspector; #endif ((UdonSharpProgramAsset)backingBehaviour.programSource)?.UpdateProgram(); }
public void AddIK() { Undo.AddComponent <InverseKinematics>(gameObject); }
private static void ConvertToHierarchyFolder() { var selectedTransforms = Selection.transforms; int selectedCount = selectedTransforms.Length; var transforms = new Transform[selectedCount]; Array.Copy(selectedTransforms, 0, transforms, 0, selectedCount); Array.Sort(transforms, SortByHierarchyOrder); for (int n = selectedCount - 1; n >= 0; n--) { var transform = transforms[n]; var gameObject = transform.gameObject; var components = gameObject.GetComponents <Component>(); // Handle GameObjects that have extraneous components besides the Transform or RectTransform component. if (components.Length > 1) { if (gameObject.IsHierarchyFolder()) { continue; } #if UNITY_2018_3_OR_NEWER if (PrefabUtility.GetPrefabInstanceStatus(gameObject) == PrefabInstanceStatus.Connected) #else if (PrefabUtility.GetPrefabType(gameObject) == PrefabType.PrefabInstance) #endif { Debug.LogWarning("Won't convert " + gameObject.name + " because it is a prefab instance and has extraneous components.", gameObject); continue; } // No benefit in flattening a target with no children. if (transform.childCount == 0) { Debug.LogWarning("Won't convert " + gameObject.name + " because it has extraneous components.", gameObject); continue; } // Never should unparent children of the Canvas. if (gameObject.GetComponent <Canvas>() != null) { Debug.LogWarning("Won't convert " + gameObject.name + " because it has the Canvas component.", gameObject); continue; } // Can't convert the target, but ask user if should flatten it instead. if (!EditorUtility.DisplayDialog("Flatten Unconvertable Target?", "Selected GameObject \"" + gameObject.name + "\" contains extraneous components (" + string.Join(", ", components.Where((c) => c != transform).Select((c) => c == null ? "<Missing Script>" : c.GetType().Name).ToArray()) + ") and as such can't directly be converted into a hierarchy folder.\n\nWould you like to create a new hierarchy folder as a parent of the target and move all " + transform.childCount + " children of the target under the new hierarchy folder?\n\nThis would result in a flatter hierarchy potentially improving performance.", "Flatten Target", "Skip")) { continue; } Undo.RegisterFullObjectHierarchyUndo(gameObject, "Convert To Hierarchy Folder"); var folder = CreateHierarchyFolderInternal(transform is RectTransform); folder.name = gameObject.name; Undo.RegisterCreatedObjectUndo(folder, "Convert To Hierarchy Folder"); var folderTransform = folder.transform; folderTransform.UndoableSetParent(transform.parent, "Convert To Hierarchy Folder"); folderTransform.SetSiblingIndex(transform.GetSiblingIndex()); transform.UndoableSetParent(folderTransform, "Convert To Hierarchy Folder"); int childCount = transform.childCount; if (childCount > 0) { for (int c = 0; c < childCount; c++) { var child = transform.GetChild(0); child.UndoableSetParent(folderTransform, "Convert To Hierarchy Folder"); } } continue; } #if UNITY_2018_3_OR_NEWER if (PrefabUtility.GetPrefabInstanceStatus(gameObject) == PrefabInstanceStatus.Connected) #else if (PrefabUtility.GetPrefabType(gameObject) == PrefabType.PrefabInstance) #endif { if (EditorUtility.DisplayDialog("Convert Prefab Instance?", "Are you sure you want to convert the selected prefab instance \"" + gameObject.name + "\" into a hierarchy folder?\n\nIf you select \"Yes\" the prefab instance root will be unpacked as part of the conversion.", "Unpack and Convert", "Skip")) { Undo.RegisterFullObjectHierarchyUndo(gameObject, "Convert To Hierarchy Folder"); #if UNITY_2018_3_OR_NEWER PrefabUtility.UnpackPrefabInstance(gameObject, PrefabUnpackMode.OutermostRoot, InteractionMode.UserAction); #else PrefabUtility.DisconnectPrefabInstance(gameObject); #endif } else { continue; } } else { Undo.RegisterFullObjectHierarchyUndo(gameObject, "Convert To Hierarchy Folder"); } Undo.AddComponent <HierarchyFolder>(gameObject); } }
void OnGUI() { // Make sure everything is initialized // Use soundbank path, because Wwise project path can be empty. if (String.IsNullOrEmpty(WwiseSetupWizard.Settings.SoundbankPath) && WwiseSetupWizard.Settings.WwiseProjectPath == null) { WwiseSetupWizard.Settings = WwiseSettings.LoadSettings(); } string initialProject = WwiseSetupWizard.Settings.WwiseProjectPath; if (VersionStyle == null) { InitGuiStyles(); } GUILayout.Label(m_WwiseVersionString, VersionStyle); DrawSettingsPart(); string newProject = WwiseSetupWizard.Settings.WwiseProjectPath; // DrawSettingsPart modifies WwiseSetupWizard.Settings.WwiseProjectPath directly. if (initialProject != newProject) { ApplyNewProject = true; } GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("OK", GUILayout.Width(60))) { if (string.IsNullOrEmpty(WwiseSetupWizard.Settings.SoundbankPath)) { EditorUtility.DisplayDialog("Error", "Please fill in the required settings", "Ok"); } if (AkWwiseSettingsWindow.m_oldCreateWwiseGlobal != WwiseSetupWizard.Settings.CreateWwiseGlobal) { AkInitializer[] AkInitializers = UnityEngine.Object.FindObjectsOfType(typeof(AkInitializer)) as AkInitializer[]; if (WwiseSetupWizard.Settings.CreateWwiseGlobal == true) { if (AkInitializers.Length == 0) { //No Wwise object in this scene, create one so that the sound engine is initialized and terminated properly even if the scenes are loaded //in the wrong order. GameObject objWwise = new GameObject("WwiseGlobal"); //Attach initializer and terminator components AkInitializer init = objWwise.AddComponent <AkInitializer>(); AkWwiseProjectInfo.GetData().CopyInitSettings(init); } } else { if (AkInitializers.Length != 0 && AkInitializers[0].gameObject.name == "WwiseGlobal") { GameObject.DestroyImmediate(AkInitializers[0].gameObject); } } } if (AkWwiseSettingsWindow.m_oldCreateWwiseListener != WwiseSetupWizard.Settings.CreateWwiseListener) { if (Camera.main != null) { AkAudioListener akListener = Camera.main.GetComponentInChildren <AkAudioListener>(); if (WwiseSetupWizard.Settings.CreateWwiseListener) { if (akListener == null) { akListener = Undo.AddComponent <AkAudioListener>(Camera.main.gameObject); AkGameObj akGameObj = akListener.GetComponentInChildren <AkGameObj>(); akGameObj.isEnvironmentAware = false; } // If Unity had already an audio listener, we want to remove it when adding our own. AudioListener unityListener = Camera.main.GetComponentInChildren <AudioListener>(); if (unityListener != null) { Component.DestroyImmediate(unityListener); } } } } if (m_oldShowMissingRigidBodyWarning != WwiseSetupWizard.Settings.ShowMissingRigidBodyWarning) { InternalEditorUtility.RepaintAllViews(); } WwiseSettings.SaveSettings(WwiseSetupWizard.Settings); CloseWindow(); // Pop the Picker window so the user can start working right away AkWwiseProjectInfo.GetData(); // Load data if (ApplyNewProject) { //Clear the data, the project path changed. AkWwiseProjectInfo.GetData().Reset(); ApplyNewProject = false; AkWwisePicker.WwiseProjectFound = true; } AkWwiseProjectInfo.Populate(); AkWwisePicker.PopulateTreeview(); AkWwisePicker.init(); } if (GUILayout.Button("Cancel", GUILayout.Width(60))) { WwiseSetupWizard.Settings = WwiseSettings.LoadSettings(true); CloseWindow(); } GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); GUILayout.EndHorizontal(); GUILayout.Space(EditorGUIUtility.standardVerticalSpacing); GUILayout.EndVertical(); }
public override void GenerateOnly() { if (voxelObject == null || voxelObjectCore.voxelData == null) { return; } var voxelData = voxelObjectCore.voxelData; //BasicCube Vector3 cubeCenter; List <Vector3> cubeVertices; List <Vector3> cubeNormals; List <int> cubeTriangles; CreateBasicCube(out cubeCenter, out cubeVertices, out cubeNormals, out cubeTriangles); #region Voxels List <Vector3> vertices = new List <Vector3>(); List <Vector3> normals = new List <Vector3>(); List <Color> colors = new List <Color>(); List <Vector4> tangents = new List <Vector4>(); List <int>[] triangles = new List <int> [voxelBase.materialData.Count]; for (int i = 0; i < triangles.Length; i++) { triangles[i] = new List <int>(); } #region Mesh Func <VoxelBaseExplosion.MeshData, VoxelBaseExplosion.MeshData> CreateMesh = (data) => { if (data == null) { data = new VoxelObjectExplosion.MeshData(); } if (data.mesh == null) { data.mesh = new Mesh(); } else { data.mesh.Clear(false); data.mesh.ClearBlendShapes(); } data.materialIndexes.Clear(); #if UNITY_2017_3_OR_NEWER data.mesh.indexFormat = vertices.Count > 65000 ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16; #endif data.mesh.vertices = vertices.ToArray(); data.mesh.normals = normals.ToArray(); data.mesh.colors = colors.ToArray(); data.mesh.tangents = tangents.ToArray(); { int materialCount = 0; for (int i = 0; i < triangles.Length; i++) { if (triangles[i].Count > 0) { materialCount++; } } data.mesh.subMeshCount = materialCount; int submesh = 0; for (int i = 0; i < triangles.Length; i++) { if (triangles[i].Count > 0) { data.materialIndexes.Add(i); data.mesh.SetTriangles(triangles[i].ToArray(), submesh++); } } } data.mesh.RecalculateBounds(); { var bounds = data.mesh.bounds; bounds.min -= Vector3.one * explosionBase.edit_velocityMax; bounds.max += Vector3.one * explosionBase.edit_velocityMax; data.mesh.bounds = bounds; } vertices.Clear(); normals.Clear(); colors.Clear(); tangents.Clear(); for (int i = 0; i < voxelBase.materialData.Count; i++) { triangles[i].Clear(); } return(data); }; #endregion { var chunkObjects = voxelObject.chunks; FlagTable3 doneTable = new FlagTable3(voxelData.voxelSize.x, voxelData.voxelSize.y, voxelData.voxelSize.z); for (int chunkIndex = 0; chunkIndex < chunkObjects.Length; chunkIndex++) { var chunkObject = chunkObjects[chunkIndex]; if (chunkObject == null) { explosionObject.chunksExplosion[chunkIndex] = null; continue; } var explosionChunk = explosionObject.chunksExplosion[chunkIndex] = chunkObject.gameObject.GetComponent <VoxelChunksObjectChunkExplosion>(); if (explosionChunk == null) { explosionChunk = explosionObject.chunksExplosion[chunkIndex] = Undo.AddComponent <VoxelChunksObjectChunkExplosion>(chunkObject.gameObject); } int meshIndex = 0; Action <int, int> AddVertex = (mat, index) => { if (explosionBase.edit_birthRate < 1f) { if (UnityEngine.Random.value >= explosionBase.edit_birthRate) { return; } } if (explosionBase.edit_visibleOnly) { if (!voxelObjectCore.IsVoxelVisible(voxelData.voxels[index].position)) { return; } } #if !UNITY_2017_3_OR_NEWER if (vertices.Count + cubeVertices.Count >= 65000) { for (int i = explosionChunk.meshes.Count; i <= meshIndex; i++) { explosionChunk.meshes.Add(null); } explosionChunk.meshes[meshIndex] = CreateMesh(explosionChunk.meshes[meshIndex]); { if (voxelBase.legacySubAssetNaming) { explosionChunk.meshes[meshIndex].mesh.name = string.Format("{0}_explosion_mesh{1}", explosionChunk.name, meshIndex); } else { explosionChunk.meshes[meshIndex].mesh.name = Path.GetFileNameWithoutExtension(voxelBase.voxelFilePath) + string.Format("_{0}_explosion_{1}", explosionChunk.name, meshIndex); } } if (!AssetDatabase.Contains(explosionChunk.meshes[meshIndex].mesh)) { voxelBaseCore.AddObjectToPrefabAsset(explosionChunk.meshes[meshIndex].mesh); } meshIndex++; } #endif var velocity = UnityEngine.Random.Range(explosionBase.edit_velocityMin, explosionBase.edit_velocityMax); var color = voxelData.palettes[voxelData.voxels[index].palette]; #if UNITY_2018_1_OR_NEWER if (EditorCommon.IsUniversalRenderPipeline() || EditorCommon.IsHighDefinitionRenderPipeline()) { color.a = velocity; } #endif var vOffset = vertices.Count; for (int i = 0; i < cubeVertices.Count; i++) { var pos = cubeVertices[i]; pos.x += voxelData.voxels[index].position.x * voxelBase.importScale.x; pos.y += voxelData.voxels[index].position.y * voxelBase.importScale.y; pos.z += voxelData.voxels[index].position.z * voxelBase.importScale.z; vertices.Add(pos); } normals.AddRange(cubeNormals); for (int j = 0; j < cubeTriangles.Count; j++) { triangles[mat].Add(vOffset + cubeTriangles[j]); } for (int j = 0; j < cubeVertices.Count; j++) { colors.Add(color); } { Vector3 center = new Vector3 ( center.x = cubeCenter.x + voxelData.voxels[index].position.x * voxelBase.importScale.x, center.y = cubeCenter.y + voxelData.voxels[index].position.y * voxelBase.importScale.y, center.z = cubeCenter.z + voxelData.voxels[index].position.z * voxelBase.importScale.z ); for (int j = 0; j < cubeVertices.Count; j++) { tangents.Add(new Vector4(center.x - vertices[vOffset + j].x, center.y - vertices[vOffset + j].y, center.z - vertices[vOffset + j].z, velocity)); } } }; if (explosionChunk.meshes == null) { explosionChunk.meshes = new List <VoxelBaseExplosion.MeshData>(); } for (int i = 1; i < voxelBase.materialData.Count; i++) { voxelBase.materialData[i].AllAction((pos) => { if (doneTable.Get(pos)) { return; } if (voxelData.chunkTable.Get(pos) != chunkObject.position) { return; } doneTable.Set(pos, true); var index = voxelData.VoxelTableContains(pos); if (index < 0) { return; } AddVertex(i, index); }); } for (int index = 0; index < voxelData.voxels.Length; index++) { var pos = voxelData.voxels[index].position; if (doneTable.Get(pos)) { continue; } if (voxelData.chunkTable.Get(pos) != chunkObject.position) { continue; } doneTable.Set(pos, true); AddVertex(0, index); } if (vertices.Count > 0) { for (int i = explosionChunk.meshes.Count; i <= meshIndex; i++) { explosionChunk.meshes.Add(null); } explosionChunk.meshes[meshIndex] = CreateMesh(explosionChunk.meshes[meshIndex]); if (!AssetDatabase.IsMainAsset(explosionChunk.meshes[meshIndex].mesh)) { if (voxelBase.legacyAssetNaming) { explosionChunk.meshes[meshIndex].mesh.name = string.Format("{0}_explosion_mesh{1}", explosionChunk.name, meshIndex); } else { explosionChunk.meshes[meshIndex].mesh.name = Path.GetFileNameWithoutExtension(voxelBase.voxelFilePath) + string.Format("_{0}_explosion_{1}", explosionChunk.name, meshIndex); } } if (!AssetDatabase.Contains(explosionChunk.meshes[meshIndex].mesh)) { voxelBaseCore.AddObjectToPrefabAsset(explosionChunk.meshes[meshIndex].mesh); } meshIndex++; } explosionChunk.meshes.RemoveRange(meshIndex, explosionChunk.meshes.Count - meshIndex); explosionChunk.chunkBasicOffset = chunkObject.basicOffset; } } #endregion #region Material explosionObject.materialMode = voxelObject.materialMode; if (voxelObject.materialMode == VoxelChunksObject.MaterialMode.Combine) { if (explosionObject.materials == null) { explosionObject.materials = new List <Material>(); } if (explosionObject.materials.Count < voxelBase.materialData.Count) { for (int i = explosionObject.materials.Count; i < voxelBase.materialData.Count; i++) { explosionObject.materials.Add(null); } } else if (explosionObject.materials.Count > voxelBase.materialData.Count) { explosionObject.materials.RemoveRange(voxelBase.materialData.Count, explosionObject.materials.Count - voxelBase.materialData.Count); } for (int i = 0; i < explosionObject.chunksExplosion.Length; i++) { explosionObject.chunksExplosion[i].materials = null; } for (int i = 0; i < voxelBase.materialData.Count; i++) { if (!voxelBase.materialIndexes.Contains(i)) { if (explosionObject.materials[i] != null) { explosionObject.materials[i] = null; voxelBaseCore.DestroyUnusedObjectInPrefabObject(); } continue; } if (explosionObject.materials[i] == null) { explosionObject.materials[i] = new Material(GetStandardShader(voxelBase.materialData[i].transparent)); } else { explosionObject.materials[i].shader = GetStandardShader(voxelBase.materialData[i].transparent); } if (!AssetDatabase.Contains(explosionObject.materials[i])) { explosionObject.materials[i].name = explosionObject.materials[i].shader.name; } if (!AssetDatabase.IsMainAsset(explosionObject.materials[i])) { if (voxelBase.legacyAssetNaming) { explosionObject.materials[i].name = string.Format("explosion_mat{0}", i); } else { explosionObject.materials[i].name = Path.GetFileNameWithoutExtension(voxelBase.voxelFilePath) + string.Format("_explosion_{0}", i); } } if (!AssetDatabase.Contains(explosionObject.materials[i])) { voxelBaseCore.AddObjectToPrefabAsset(explosionObject.materials[i]); } } } else if (voxelObject.materialMode == VoxelChunksObject.MaterialMode.Individual) { explosionObject.materials = null; for (int chunkIndex = 0; chunkIndex < explosionObject.chunksExplosion.Length; chunkIndex++) { var explosionChunk = explosionObject.chunksExplosion[chunkIndex]; if (explosionChunk.materials == null) { explosionChunk.materials = new List <Material>(); } if (explosionChunk.materials.Count < voxelBase.materialData.Count) { for (int i = explosionChunk.materials.Count; i < voxelBase.materialData.Count; i++) { explosionChunk.materials.Add(null); } } else if (explosionChunk.materials.Count > voxelBase.materialData.Count) { explosionChunk.materials.RemoveRange(voxelBase.materialData.Count, explosionChunk.materials.Count - voxelBase.materialData.Count); } for (int i = 0; i < voxelBase.materialData.Count; i++) { if (!voxelObject.chunks[chunkIndex].materialIndexes.Contains(i)) { if (explosionChunk.materials[i] != null) { explosionChunk.materials[i] = null; voxelBaseCore.DestroyUnusedObjectInPrefabObject(); } continue; } if (explosionChunk.materials[i] == null) { explosionChunk.materials[i] = new Material(GetStandardShader(voxelBase.materialData[i].transparent)); } else { explosionChunk.materials[i].shader = GetStandardShader(voxelBase.materialData[i].transparent); } if (!AssetDatabase.Contains(explosionChunk.materials[i])) { explosionChunk.materials[i].name = explosionChunk.materials[i].shader.name; } if (!AssetDatabase.IsMainAsset(explosionChunk.materials[i])) { if (voxelBase.legacyAssetNaming) { explosionChunk.materials[i].name = string.Format("{0}_explosion_mat{1}", explosionChunk.name, i); } else { explosionChunk.materials[i].name = Path.GetFileNameWithoutExtension(voxelBase.voxelFilePath) + string.Format("_{0}_explosion_{1}", explosionChunk.name, i); } } if (!AssetDatabase.Contains(explosionChunk.materials[i])) { voxelBaseCore.AddObjectToPrefabAsset(explosionChunk.materials[i]); } } } } else { Assert.IsTrue(false); } #endregion }
private void ApplyPropertiesToGameObject(int value) { if (!Selection.activeTransform.GetComponent <Collider> ()) { if (EditorUtility.DisplayDialog("INFO : Action none available" , "You need to have a Collider attached to the selected Object. Collider could be :" + "\n" + "\nBox Collider, mesh collider, capsule collider, sphere collider." , "Continue")) { } } else { Undo.RegisterFullObjectHierarchyUndo(Selection.activeTransform, Selection.activeTransform.name); if (Selection.activeTransform.GetComponent <TextProperties> ()) { DestroyImmediate(Selection.activeTransform.GetComponent <TextProperties> ()); } if (Selection.activeTransform.GetComponent <isObjectActivated> ()) { DestroyImmediate(Selection.activeTransform.GetComponent <isObjectActivated> ()); } if (Selection.activeTransform.GetComponent <SaveData> ()) { DestroyImmediate(Selection.activeTransform.GetComponent <SaveData> ()); } if (!Selection.activeTransform.GetComponent <TextProperties> ()) { Undo.AddComponent(Selection.activeGameObject, typeof(TextProperties)); } TextProperties item = Selection.activeTransform.GetComponent <TextProperties> (); Undo.RegisterFullObjectHierarchyUndo(item, item.name); item.uniqueID = diaryList.GetArrayElementAtIndex(currentLanguage.intValue).FindPropertyRelative("_languageSlot").GetArrayElementAtIndex(value).FindPropertyRelative("uniqueItemID").intValue; item.managerID = value; item.textList = _textList; item.gameObject.tag = "Item"; item.gameObject.isStatic = false; //Debug.Log (editorType.intValue); item.editorType = editorType.intValue; Selection.activeTransform.GetComponent <Collider> ().isTrigger = true; if (!Selection.activeTransform.GetComponent <isObjectActivated> () && diaryList.GetArrayElementAtIndex(currentLanguage.intValue).FindPropertyRelative("_languageSlot").GetArrayElementAtIndex(value).FindPropertyRelative("showInInventory").boolValue) { Undo.AddComponent(Selection.activeGameObject, typeof(isObjectActivated)); if (!Selection.activeTransform.GetComponent <SaveData> ()) { Undo.AddComponent(Selection.activeGameObject, typeof(SaveData)); } MonoBehaviour[] comp3 = Selection.activeTransform.GetComponents <MonoBehaviour> (); // find all the MonoBehaviour in a gameObject for (var i = 0; i < comp3.Length; i++) { if (comp3 [i].GetType().ToString() == "isObjectActivated") { Selection.activeTransform.GetComponent <SaveData> ().isObjectActivatedIndex = i; Selection.activeTransform.GetComponent <SaveData> ().b_isObjectActivated = true; Debug.Log("Method " + i + " : " + comp3 [i].GetType().ToString()); break; } } } } }
internal static UdonBehaviour[] ConvertToUdonBehavioursInternal(UdonSharpBehaviour[] components, bool shouldUndo, bool showPrompts, bool convertChildren) { components = components.Distinct().ToArray(); if (showPrompts) { HashSet <UdonSharpBehaviour> allReferencedBehaviours = new HashSet <UdonSharpBehaviour>(); // Check if any of these need child component conversion foreach (UdonSharpBehaviour targetObject in components) { HashSet <UdonSharpBehaviour> referencedBehaviours = new HashSet <UdonSharpBehaviour>(); CollectUdonSharpBehaviourReferencesInternal(targetObject, referencedBehaviours); if (referencedBehaviours.Count > 1) { foreach (UdonSharpBehaviour referencedBehaviour in referencedBehaviours) { if (referencedBehaviour != targetObject) { allReferencedBehaviours.Add(referencedBehaviour); } } } } if (allReferencedBehaviours.Count > 0) { // This is an absolute mess, it should probably just be simplified to counting the number of affected behaviours string referencedBehaviourStr; if (allReferencedBehaviours.Count <= 2) { referencedBehaviourStr = string.Join(", ", allReferencedBehaviours.Select(e => $"'{e.ToString()}'")); } else { referencedBehaviourStr = $"{allReferencedBehaviours.Count} behaviours"; } string rootBehaviourStr; if (components.Length <= 2) { rootBehaviourStr = $"{string.Join(", ", components.Select(e => $"'{e.ToString()}'"))} reference{(components.Length == 1 ? "s" : "")} "; } else { rootBehaviourStr = $"{components.Length} behaviours to convert reference "; } string messageStr = $"{rootBehaviourStr}{referencedBehaviourStr}. Do you want to convert all referenced behaviours as well? If no, references to these behaviours will be set to null."; int result = EditorUtility.DisplayDialogComplex("Dependent behaviours found", messageStr, "Yes", "Cancel", "No"); if (result == 2) // No { convertChildren = false; } else if (result == 1) // Cancel { return(null); } } } if (shouldUndo) { Undo.RegisterCompleteObjectUndo(components, "Convert to UdonBehaviour"); } List <UdonBehaviour> createdComponents = new List <UdonBehaviour>(); foreach (UdonSharpBehaviour targetObject in components) { MonoScript behaviourScript = MonoScript.FromMonoBehaviour(targetObject); UdonSharpProgramAsset programAsset = GetUdonSharpProgramAsset(behaviourScript); if (programAsset == null) { if (showPrompts) { string scriptPath = AssetDatabase.GetAssetPath(behaviourScript); string scriptDirectory = Path.GetDirectoryName(scriptPath); string scriptFileName = Path.GetFileNameWithoutExtension(scriptPath); string assetPath = Path.Combine(scriptDirectory, $"{scriptFileName}.asset").Replace('\\', '/'); if (EditorUtility.DisplayDialog("No linked program asset", $"There was no UdonSharpProgramAsset found for '{behaviourScript.GetClass()}', do you want to create one?", "Ok", "Cancel")) { if (AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(assetPath) != null) { if (!EditorUtility.DisplayDialog("Existing file found", $"Asset file {assetPath} already exists, do you want to overwrite it?", "Ok", "Cancel")) { continue; } } } else { continue; } programAsset = ScriptableObject.CreateInstance <UdonSharpProgramAsset>(); programAsset.sourceCsScript = behaviourScript; AssetDatabase.CreateAsset(programAsset, assetPath); AssetDatabase.SaveAssets(); UdonSharpProgramAsset.ClearProgramAssetCache(); programAsset.CompileCsProgram(); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); } else { Debug.LogWarning($"Could not convert U# behaviour '{behaviourScript.GetClass()}' on '{targetObject.gameObject}' because it does not have a corresponding UdonSharpProgramAsset"); continue; } } GameObject targetGameObject = targetObject.gameObject; UdonBehaviour udonBehaviour = null; if (shouldUndo) { udonBehaviour = Undo.AddComponent <UdonBehaviour>(targetGameObject); } else { udonBehaviour = targetGameObject.AddComponent <UdonBehaviour>(); } udonBehaviour.programSource = programAsset; #pragma warning disable CS0618 // Type or member is obsolete udonBehaviour.SynchronizePosition = false; udonBehaviour.AllowCollisionOwnershipTransfer = false; #pragma warning restore CS0618 // Type or member is obsolete udonBehaviour.Reliable = programAsset.behaviourSyncMode == BehaviourSyncMode.Manual; //if (shouldUndo) // Undo.RegisterCompleteObjectUndo(targetObject, "Convert C# to U# behaviour"); UdonSharpEditorUtility.SetBackingUdonBehaviour(targetObject, udonBehaviour); try { if (convertChildren) { UdonSharpEditorUtility.CopyProxyToUdon(targetObject, shouldUndo ? ProxySerializationPolicy.AllWithCreateUndo : ProxySerializationPolicy.AllWithCreate); } else { UdonSharpEditorUtility.CopyProxyToUdon(targetObject, ProxySerializationPolicy.RootOnly); } } catch (System.Exception e) { Debug.LogError(e); } UdonSharpEditorUtility.SetBackingUdonBehaviour(targetObject, null); System.Type behaviourType = targetObject.GetType(); UdonSharpBehaviour newProxy; SetIgnoreEvents(true); try { if (shouldUndo) { newProxy = (UdonSharpBehaviour)Undo.AddComponent(targetObject.gameObject, behaviourType); } else { newProxy = (UdonSharpBehaviour)targetObject.gameObject.AddComponent(behaviourType); } UdonSharpEditorUtility.SetBackingUdonBehaviour(newProxy, udonBehaviour); try { UdonSharpEditorUtility.CopyUdonToProxy(newProxy); } catch (System.Exception e) { Debug.LogError(e); } if (shouldUndo) { Undo.DestroyObjectImmediate(targetObject); } else { Object.DestroyImmediate(targetObject); } newProxy.hideFlags = HideFlags.DontSaveInBuild | #if !UDONSHARP_DEBUG HideFlags.HideInInspector | #endif HideFlags.DontSaveInEditor; newProxy.enabled = false; } finally { SetIgnoreEvents(false); } createdComponents.Add(udonBehaviour); } return(createdComponents.ToArray()); }
public static void Migrate() { int oldUndoIndex = Undo.GetCurrentGroup(); Undo.IncrementCurrentGroup(); #if !UNITY_4_6 || UNITY_4_7 Undo.SetCurrentGroupName("FMOD Studio Integration Migration"); #endif Settings settings = Settings.Instance; var prefKey = "FMODStudioProjectPath_" + Application.dataPath; var prefValue = EditorPrefs.GetString(prefKey); if (prefValue != null) { settings.SourceBankPath = prefValue as string; settings.SourceBankPath += "/Build"; settings.HasSourceProject = false; } // for each level EditorApplication.SaveCurrentSceneIfUserWantsTo(); var scenes = AssetDatabase.FindAssets("*.scene"); foreach (string scene in scenes) { if (!EditorUtility.DisplayDialog("FMOD Studio Integration Migration", String.Format("Migrate scene {0}", AssetDatabase.GUIDToAssetPath(scene)), "OK", "Cancel")) { continue; } EditorApplication.OpenScene(AssetDatabase.GUIDToAssetPath(scene)); var emitters = FindObjectsOfType <FMOD_StudioEventEmitter>(); foreach (var emitter in emitters) { GameObject parent = emitter.gameObject; bool startOnAwake = emitter.startEventOnAwake; string path = null; if (emitter.asset != null) { path = emitter.asset.path; } else if (!String.IsNullOrEmpty(emitter.path)) { path = emitter.path; } else { continue; } Undo.DestroyObjectImmediate(emitter); var newEmitter = Undo.AddComponent <StudioEventEmitter>(parent); newEmitter.Event = path; newEmitter.PlayEvent = startOnAwake ? EmitterGameEvent.LevelStart : EmitterGameEvent.None; newEmitter.PlayEvent = startOnAwake ? EmitterGameEvent.LevelEnd : EmitterGameEvent.None; } var listeners = FindObjectsOfType <FMOD_Listener>(); foreach (var listener in listeners) { GameObject parent = listener.gameObject; foreach (var plugin in listener.pluginPaths) { if (!settings.Plugins.Contains(plugin)) { settings.Plugins.Add(plugin); } } Undo.DestroyObjectImmediate(listener); Undo.AddComponent <StudioListener>(parent); } foreach (var custom in CustomMigrationEntries) { var objects = FindObjectsOfType(custom.ScriptClass); foreach (var obj in objects) { var serializedObj = new SerializedObject(obj); var oldProp = serializedObj.FindProperty(custom.OldProperty); if (oldProp == null || oldProp.propertyType != SerializedPropertyType.ObjectReference || (oldProp.objectReferenceValue != null && oldProp.objectReferenceValue.GetType() != typeof(FMODAsset))) { UnityEngine.Debug.LogWarning(String.Format("FMOD Studio Migration: Cannot find property {0} of type FMODAsset on script {1}", custom.OldProperty, custom.ScriptClass.ToString())); continue; } var newProp = serializedObj.FindProperty(custom.NewProperty); if (newProp == null || newProp.propertyType != SerializedPropertyType.String) { UnityEngine.Debug.LogWarning(String.Format("FMOD Studio Migration: Cannot find property {0} of type string on script {1}", custom.NewProperty, custom.ScriptClass.ToString())); continue; } var oldAsset = oldProp.objectReferenceValue as FMODAsset; if (oldAsset != null) { newProp.stringValue = oldAsset.path; } oldProp.objectReferenceValue = null; serializedObj.ApplyModifiedProperties(); } } EditorApplication.SaveCurrentSceneIfUserWantsTo(); } EditorUtility.SetDirty(settings); AssetDatabase.DeleteAsset("Assets/FMODAssets"); AssetDatabase.Refresh(); Undo.CollapseUndoOperations(oldUndoIndex); }
public void CreateRotatedBoxCollider(Transform attachTo) { Vector3 center = new Vector3(); Vector3 size = new Vector3(); Vector3 cornerVector = new Vector3(); List <Vector3> localVerts = new List <Vector3>(); foreach (Vector3 point in SelectedVertices) { localVerts.Add(this.transform.InverseTransformPoint(point)); //transforms to local vertexs } float minDistance = Mathf.Infinity; foreach (Vector3 vectorA in SelectedVertices) //finds corner vertex by calculating max distance. corner will have least distance. { float distance = 0; foreach (Vector3 vectorB in SelectedVertices) { if (SelectedVertices.IndexOf(vectorA) != SelectedVertices.IndexOf(vectorB)) { distance += Vector3.Distance(vectorA, vectorB); } } if (distance < minDistance) { cornerVector = vectorA; minDistance = distance; } } float maxDistance = 0; Vector3 forwardVector = new Vector3(); Vector3 forwardVertex = new Vector3(); foreach (Vector3 vector in SelectedVertices) //calculates forward vector for quaternion creation. { if (SelectedVertices.IndexOf(cornerVector) != SelectedVertices.IndexOf(vector)) { float distance = Vector3.Distance(cornerVector, vector); if (distance > maxDistance) { maxDistance = distance; forwardVector = vector - cornerVector; forwardVertex = vector; } } } Vector3 otherVector = new Vector3(); bool isOtherVectorAlreadyOrtho = false; float dotproduct = 100000000F; foreach (Vector3 vector in SelectedVertices) //calculates the other vector used to get CrossProduct for othogonal vector for quaternion creation. { if (SelectedVertices.IndexOf(vector) != SelectedVertices.IndexOf(forwardVertex) && SelectedVertices.IndexOf(vector) != SelectedVertices.IndexOf(cornerVector)) { Vector3 otherVector2 = vector - cornerVector; if (Vector3.Dot(forwardVector, otherVector2) == 0F) //ie is already orthogonal { isOtherVectorAlreadyOrtho = true; otherVector = otherVector2; break; } else //checks to see which is closest to orthogonal already to use that factor in ortho calculation for improved accuracy. { float dot = Vector3.Dot(Vector3.forward, otherVector2); if (dot < dotproduct) { otherVector = otherVector2; dotproduct = dot; } } } } Vector3 orthoVector = new Vector3(); if (isOtherVectorAlreadyOrtho) { orthoVector = otherVector; } else { orthoVector = Vector3.Cross(forwardVector, otherVector); } GameObject rotatedCollider = new GameObject("RotatedCollider"); Undo.RegisterCreatedObjectUndo(rotatedCollider, "Created rotated collider"); Undo.SetTransformParent(rotatedCollider.transform, attachTo, "RotatedCollider"); // rotatedCollider.transform.SetParent(attachTo); rotatedCollider.transform.localPosition = Vector3.zero; Quaternion q = new Quaternion(); q.SetLookRotation(forwardVector, orthoVector); rotatedCollider.transform.rotation = q; rotatedCollider.layer = 30; //for use in selection by raycast. Undo.AddComponent <BoxCollider>(rotatedCollider); BoxCollider box = rotatedCollider.GetComponent <BoxCollider>(); int cornerIndex = SelectedVertices.IndexOf(cornerVector); List <Vector3> localBoxVerts = new List <Vector3>(); foreach (Vector3 vert in SelectedVertices) { localBoxVerts.Add(rotatedCollider.transform.InverseTransformPoint(vert)); } foreach (Vector3 vertex in SelectedVertices) { size += rotatedCollider.transform.InverseTransformPoint(vertex) - rotatedCollider.transform.InverseTransformPoint(SelectedVertices[cornerIndex]); if (SelectedVertices.IndexOf(vertex) != cornerIndex) { center += (vertex - SelectedVertices[cornerIndex]) / 2; } } center += SelectedVertices[cornerIndex]; box.size = size; box.center = rotatedCollider.transform.InverseTransformPoint(center); SelectedVertices.Clear(); Selection.activeGameObject = attachTo.gameObject; }