private void CreateStateMachine() { if (this.m_AvatarPreview == null || !((UnityEngine.Object) this.m_AvatarPreview.Animator != (UnityEngine.Object) null)) return; if ((UnityEngine.Object) this.m_Controller == (UnityEngine.Object) null) { this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("preview"); this.m_StateMachine = this.m_Controller.layers[0].stateMachine; this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("preview"); this.m_State.pushUndo = false; this.m_State.motion = (Motion) this.m_BlendTree; this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; this.m_State.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_Controller.OnAnimatorControllerDirty += new System.Action(this.ControllerDirty); this.m_ControllerIsDirty = false; } if (!((UnityEngine.Object) AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != (UnityEngine.Object) this.m_Controller)) return; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); }
private void CopyStateForPreview(AnimatorState src, ref AnimatorState dst) { dst.iKOnFeet = src.iKOnFeet; dst.speed = src.speed; dst.mirror = src.mirror; dst.motion = src.motion; }
private void CreateStateMachine() { if ((this.m_AvatarPreview != null) && (this.m_AvatarPreview.Animator != null)) { if (this.m_Controller == null) { this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("preview"); this.m_StateMachine = this.m_Controller.layers[0].stateMachine; this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("preview"); this.m_State.pushUndo = false; this.m_State.motion = this.m_BlendTree; this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; this.m_State.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_Controller.OnAnimatorControllerDirty = (Action) Delegate.Combine(this.m_Controller.OnAnimatorControllerDirty, new Action(this, (IntPtr) this.ControllerDirty)); this.m_ControllerIsDirty = false; } if (AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) { AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); } } }
public TransitionEditionContext(AnimatorTransitionBase aTransition, AnimatorState aSourceState, AnimatorStateMachine aSourceStateMachine, AnimatorStateMachine aOwnerStateMachine) { this.transition = aTransition; this.sourceState = aSourceState; this.sourceStateMachine = aSourceStateMachine; this.ownerStateMachine = aOwnerStateMachine; this.BuildNames(); }
private void Init() { this.m_SrcState = null; this.m_DstState = null; this.m_TransitionDuration = 0f; this.m_TransitionOffset = 0f; this.m_ExitTime = 0.5f; }
private void ClearStateMachine() { if (this.m_Animator != null) { AnimatorController.SetAnimatorController(this.m_Animator, null); } UnityEngine.Object.DestroyImmediate(this.m_Controller); UnityEngine.Object.DestroyImmediate(this.m_State); this.m_StateMachine = null; this.m_Controller = null; this.m_State = null; }
void Reset() { displayEvents = null; targetController = null; targetStateMachine = null; targetState = null; targetEvent = null; selectedLayer = 0; selectedState = 0; selectedEvent = 0; MecanimEventEditorPopup.Destroy(); }
public StateMachineBehaviour[] GetOverrideBehaviours(AnimatorState state) { if (this.m_Behaviours != null) { foreach (StateBehavioursPair pair in this.m_Behaviours) { if (pair.m_State == state) { return pair.m_Behaviours; } } } return new StateMachineBehaviour[0]; }
public Motion GetOverrideMotion(AnimatorState state) { if (this.m_Motions != null) { foreach (StateMotionPair pair in this.m_Motions) { if (pair.m_State == state) { return pair.m_Motion; } } } return null; }
public void Set(AnimatorStateTransition transition, AnimatorState srcState, AnimatorState dstState) { if (transition != null) { this.m_SrcState = srcState; this.m_DstState = dstState; this.m_TransitionDuration = transition.duration; this.m_TransitionOffset = transition.offset; this.m_ExitTime = 0.5f; } else { this.Init(); } }
private void ClearStateMachine() { if (this.m_Animator != null) { AnimatorController.SetAnimatorController(this.m_Animator, null); } if (this.m_Controller != null) { this.m_Controller.OnAnimatorControllerDirty = (System.Action) Delegate.Remove(this.m_Controller.OnAnimatorControllerDirty, new System.Action(this.ControllerDirty)); } UnityEngine.Object.DestroyImmediate(this.m_Controller); UnityEngine.Object.DestroyImmediate(this.m_State); this.m_StateMachine = null; this.m_Controller = null; this.m_State = null; }
private void ClearStateMachine() { if ((this.m_AvatarPreview != null) && (this.m_AvatarPreview.Animator != null)) { AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); } if (this.m_Controller != null) { this.m_Controller.OnAnimatorControllerDirty = (Action) Delegate.Remove(this.m_Controller.OnAnimatorControllerDirty, new Action(this, (IntPtr) this.ControllerDirty)); } Object.DestroyImmediate(this.m_Controller); Object.DestroyImmediate(this.m_State); this.m_StateMachine = null; this.m_Controller = null; this.m_State = null; }
private void ClearController() { if ((this.m_AvatarPreview != null) && (this.m_AvatarPreview.Animator != null)) { AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); } UnityEngine.Object.DestroyImmediate(this.m_Controller); UnityEngine.Object.DestroyImmediate(this.m_SrcState); UnityEngine.Object.DestroyImmediate(this.m_DstState); UnityEngine.Object.DestroyImmediate(this.m_Transition); this.m_StateMachine = null; this.m_Controller = null; this.m_SrcState = null; this.m_DstState = null; this.m_Transition = null; }
void DrawClip(AnimatorState animaState, AnimationClip motion, AnimatorStateMachine stateMachine) { CreateObjectField(animaState); CreateObjectField(motion); if (null != animaState) { EditorGUI.indentLevel = 0; var transitions = animaState.transitions; BeginHorizontal(); DoButton("SelectAll", () => { Selection.objects = transitions; }); DoButton<AnimatorStateTransition[], string>("ExitTime", BatchChangeProperty, transitions, "ExitTime"); DoButton("FixedDuration", () => { }); DoButton("Trans Duration", () => { }); DoButton("Trans Offset", () => { }); EndHorizontal(); EditorGUI.indentLevel = 2; for (int i = 0; i < transitions.Length; i++) { BeginHorizontal(); CreateObjectField(transitions[i]); CreateLabel(transitions[i].GetDisplayName(stateMachine)); EndHorizontal(); } EditorGUI.indentLevel = 0; } if (null != motion) { EditorGUILayout.BeginHorizontal(); CreateLabel(motion.name); CreateLabel(motion.averageDuration.ToString()); CreateLabel(motion.isLooping.ToString()); EditorGUILayout.EndHorizontal(); } }
public void SetOverrideBehaviours(AnimatorState state, StateMachineBehaviour[] behaviours) { StateBehavioursPair pair; if (this.m_Behaviours == null) { this.m_Behaviours = new StateBehavioursPair[0]; } for (int i = 0; i < this.m_Behaviours.Length; i++) { if (this.m_Behaviours[i].m_State == state) { this.m_Behaviours[i].m_Behaviours = behaviours; return; } } pair.m_State = state; pair.m_Behaviours = behaviours; ArrayUtility.Add<StateBehavioursPair>(ref this.m_Behaviours, pair); }
public void SetOverrideMotion(AnimatorState state, Motion motion) { StateMotionPair pair; if (this.m_Motions == null) { this.m_Motions = new StateMotionPair[0]; } for (int i = 0; i < this.m_Motions.Length; i++) { if (this.m_Motions[i].m_State == state) { this.m_Motions[i].m_Motion = motion; return; } } pair.m_State = state; pair.m_Motion = motion; ArrayUtility.Add<StateMotionPair>(ref this.m_Motions, pair); }
private void CreateStateMachine() { if (!((UnityEngine.Object) this.m_Controller == (UnityEngine.Object) null)) return; this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("viz"); this.m_StateMachine = this.m_Controller.layers[0].stateMachine; this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("viz"); this.m_State.pushUndo = false; this.m_State.motion = (Motion) this.m_BlendTree; this.m_State.iKOnFeet = false; this.m_State.hideFlags = HideFlags.HideAndDontSave; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; AnimatorController.SetAnimatorController(this.m_Animator, this.m_Controller); this.m_Controller.OnAnimatorControllerDirty += new System.Action(this.ControllerDirty); this.m_ControllerIsDirty = false; }
private void CreateStateMachine() { if (this.m_Controller == null) { this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("viz"); this.m_StateMachine = this.m_Controller.layers[0].stateMachine; this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("viz"); this.m_State.pushUndo = false; this.m_State.motion = this.m_BlendTree; this.m_State.iKOnFeet = false; this.m_State.hideFlags = HideFlags.HideAndDontSave; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; AnimatorController.SetAnimatorController(this.m_Animator, this.m_Controller); this.m_Controller.OnAnimatorControllerDirty = (Action) Delegate.Combine(this.m_Controller.OnAnimatorControllerDirty, new Action(this, (IntPtr) this.ControllerDirty)); this.m_ControllerIsDirty = false; } }
private void CreateStateMachine() { if ((this.m_Animator != null) && (this.m_Controller == null)) { this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("node"); this.m_StateMachine = this.m_Controller.layers[0].stateMachine; this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("node", new Vector3()); this.m_State.pushUndo = false; this.m_State.motion = this.motion; this.m_State.hideFlags = HideFlags.DontSave; this.m_Controller.hideFlags = HideFlags.DontSave; this.m_StateMachine.hideFlags = HideFlags.DontSave; AnimatorController.SetAnimatorController(this.m_Animator, this.m_Controller); this.m_Animator.Update(0f); this.m_Controller.OnAnimatorControllerDirty = (Action) Delegate.Combine(this.m_Controller.OnAnimatorControllerDirty, new Action(this, (IntPtr) this.ControllerDirty)); this.m_ControllerIsDirty = false; } }
private void ClearStateMachine() { if (avatarPreview != null && avatarPreview.Animator != null) { AnimatorController.SetAnimatorController(avatarPreview.Animator, null); } if (this.controller != null) { controller.RemoveOnAnimatorControllerDirtyCallback(this.ControllerDitry); } Object.DestroyImmediate(this.controller); //Object.DestroyImmediate(this.stateMachine); Object.DestroyImmediate(this.state); stateMachine = null; controller = null; state = null; }
private void DestroyController() { if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) { UnityEditor.Animations.AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); } UnityEngine.Object.DestroyImmediate(this.m_Controller); UnityEngine.Object.DestroyImmediate(this.m_State); this.m_Controller = null; this.m_StateMachine = null; this.m_State = null; }
public int HandleState(ref AnimatorState state) { bool stateExist; var stateInfo = controllerInfo.states.AddObject(state, out stateExist); if (!stateExist) { stateInfo.Value.AddField("name", state.name); var stateJSON = stateInfo.Value; JSONObject stateTransitions = new JSONObject(JSONObject.Type.ARRAY); for (int j = 0; j < state.transitions.Length; j++) { AnimatorStateTransition trans = state.transitions[j]; stateTransitions.Add(HandleStateTransition(state.name, ref trans)); } stateJSON.AddField("transitions", stateTransitions); // animationClip Motion motion = state.motion; if (motion == null) { stateJSON.AddField("motion", new JSONObject(JSONObject.Type.NULL)); } else if (motion.GetType() == typeof(AnimationClip)) { JSONObject clipJSON = new JSONObject(JSONObject.Type.OBJECT); AnimationClip clip = motion as AnimationClip; if (handleBeforeAnimationClip != null && !handleBeforeAnimationClip(clip, state, gameObject)) { // 如果return false,说明这个animationclip被外面所接管 clipJSON.AddField("id", ""); } else { string clipUid = HandleAnimationClip(ref clip); clipJSON.AddField("id", clipUid); } clipJSON.AddField("type", "AnimationClip"); stateJSON.AddField("motion", clipJSON); } else if (motion.GetType() == typeof(BlendTree)) { JSONObject btJSON = new JSONObject(JSONObject.Type.OBJECT); BlendTree bt = motion as BlendTree; btJSON.AddField("type", "BlendTree"); btJSON.AddField("id", TraverseBlendTree(ref bt)); stateJSON.AddField("motion", btJSON); } stateJSON.AddField("cycleOffset", state.cycleOffset); if (state.cycleOffsetParameterActive) { stateJSON.AddField("cycleOffsetParameter", state.cycleOffsetParameter); } else { stateJSON.AddField("cycleOffsetParameter", new JSONObject(JSONObject.Type.NULL)); } stateJSON.AddField("mirror", state.mirror); if (state.mirrorParameterActive) { stateJSON.AddField("mirrorParameter", state.mirrorParameter); } else { stateJSON.AddField("mirrorParameter", new JSONObject(JSONObject.Type.NULL)); } stateInfo.Value.AddField("speed", state.speed); if (state.speedParameterActive) { stateJSON.AddField("speedParameter", state.speedParameter); } else { stateJSON.AddField("speedParameter", new JSONObject(JSONObject.Type.NULL)); } #if UNITY_2017_1_OR_NEWER if (state.timeParameterActive) { stateJSON.AddField("timeParameter", state.timeParameter); } else { #endif stateJSON.AddField("timeParameter", new JSONObject(JSONObject.Type.NULL)); #if UNITY_2017_1_OR_NEWER } #endif return(stateInfo.Key); } else { return(stateInfo.Key); } }
/************************************************************************************************/ public AnimatorController CreateAnimatorController() { // The new controller that will be created based on Manager animations AnimatorController newController = new AnimatorController(); newController.name = DEFAULT_CONTROLLER_NAME; newController.AddLayer("DefaultLayer"); // Add a parameter that will determine the animation states AnimatorControllerParameter animatorParameter = new AnimatorControllerParameter(); animatorParameter.type = AnimatorControllerParameterType.Int; animatorParameter.name = "TextAnimation"; animatorParameter.defaultInt = 999; newController.AddParameter(animatorParameter); // Add state machine AnimatorStateMachine rootStateMachine = newController.layers[0].stateMachine; AnimatorStateMachine stateMachine = rootStateMachine.AddStateMachine("TextAnimationStateMachine"); // Create a default state to prevent animation auto playing index 0 AnimatorState waitingState = stateMachine.AddState("Waiting"); //foreach (AnimationClip clip in DamageNumberManager.instance.animations) for (int i = 0; i < myScript.animations.Length; i++) { AnimationClip clip = myScript.animations[i]; // Add new state based on the AnimationClip AnimatorState state = stateMachine.AddState(clip.name); state.motion = clip; // Create transition from "Waiting" to the new state AnimatorStateTransition transition = waitingState.AddTransition(state, false); transition.AddCondition(AnimatorConditionMode.Equals, i, "TextAnimation"); } //// Save OR update the new AnimatorController as an asset (.controller) // Search if there is already an AnimatorController (and get its path if so) string assetPath = null; if (myScript.animatorOverrideController != null) { assetPath = AssetDatabase.GetAssetPath(myScript.animatorOverrideController.runtimeAnimatorController); } Object existingController = AssetDatabase.LoadAssetAtPath <Object>(assetPath); if (existingController == null) { // Create the new AnimatorController in the specified default directory AssetDatabase.CreateAsset(newController, DEFAULT_CONTROLLER_PATH + DEFAULT_CONTROLLER_NAME + ".controller"); existingController = newController; Debug.LogError("AnimatorController not found. Creating new one in " + DEFAULT_CONTROLLER_PATH + " directory."); } else { // Update the existing AnimatorController copy with latest data EditorUtility.CopySerialized(newController, existingController); Debug.Log("Updated existing AnimatorController found at " + assetPath + "."); } // Make sure the returned controller refers to the generated 'asset', not the controller 'within this scope' AnimatorController updatedController_asset = (AnimatorController)existingController; AssetDatabase.SaveAssets(); return(updatedController_asset); }
private static bool GetFullPathRecursively(AnimatorStateMachine parentSM, AnimatorState state, List<string> pathElems) { for (int i = 0 ;i < parentSM.states.Length; i++) { if (parentSM.states[i].state == state) { pathElems.Add(parentSM.name); pathElems.Add(state.name); return true; } } for (int i = 0; i < parentSM.stateMachines.Length; i++) { if (GetFullPathRecursively(parentSM.stateMachines[i].stateMachine, state, pathElems)) { pathElems.Insert(0, parentSM.name); return true; } } return false; }
public static void CreateAnimFile(ArmatureEditor armatureEditor) { changedSpriteFramesKV = new Dictionary <string, SpriteFrame>(); changedSpriteMeshsKV = new Dictionary <string, SpriteMesh>(); string path = AssetDatabase.GetAssetPath(armatureEditor.animTextAsset); path = path.Substring(0, path.LastIndexOf('/')) + "/Anims"; if (!AssetDatabase.IsValidFolder(path)) { Directory.CreateDirectory(path); } path += "/"; Animator animator = armatureEditor.armature.gameObject.AddComponent <Animator>(); AnimatorController controller = AssetDatabase.LoadAssetAtPath <AnimatorController>(path + armatureEditor.armature.name + ".controller"); AnimatorStateMachine rootStateMachine = null; if (controller == null) { controller = AnimatorController.CreateAnimatorControllerAtPath(path + armatureEditor.armature.name + ".controller"); rootStateMachine = controller.layers[0].stateMachine; } animator.runtimeAnimatorController = controller; if (armatureEditor.armatureData.animDatas != null) { int len = armatureEditor.armatureData.animDatas.Length; for (int i = 0; i < len; ++i) { DragonBoneData.AnimationData animationData = armatureEditor.armatureData.animDatas[i]; string clipPath = path + animationData.name + ".anim"; if (len > 1) { clipPath = path + armatureEditor.armature.name + "_" + animationData.name + ".anim"; } AnimationClip clip = AssetDatabase.LoadAssetAtPath <AnimationClip>(clipPath); if (clip == null) { clip = new AnimationClip(); AssetDatabase.CreateAsset(clip, clipPath); } else { clip.ClearCurves(); } clip.name = animationData.name; clip.frameRate = armatureEditor.armatureData.frameRate; CreateAnimBoneAndSlot(armatureEditor, clip, animationData.boneDatas, armatureEditor.bonesKV, true); CreateAnimBoneAndSlot(armatureEditor, clip, animationData.slotDatas, armatureEditor.slotsKV, false); CreateAnimBoneAndSlot(armatureEditor, clip, animationData.ffdDatas, armatureEditor.slotsKV, false, true); SetDragonBoneArmature(armatureEditor); SetEvent(armatureEditor, clip, animationData.keyDatas); SerializedObject serializedClip = new SerializedObject(clip); AnimationClipSettings clipSettings = new AnimationClipSettings(serializedClip.FindProperty("m_AnimationClipSettings")); clipSettings.loopTime = animationData.playTimes == 0; serializedClip.ApplyModifiedProperties(); if (rootStateMachine != null) { AnimatorState state = rootStateMachine.AddState(clip.name); state.motion = clip; } } AssetDatabase.SaveAssets(); } if (rootStateMachine != null && rootStateMachine.states != null && rootStateMachine.states.Length > 0) { rootStateMachine.defaultState = rootStateMachine.states[0].state; } //createAvatar if (armatureEditor.createAvatar) { CreateAvatar(armatureEditor, animator, path); } }
private static void copyController(AnimatorController originController, AnimatorController newController) { //parameter foreach (var parameter in originController.parameters) { if (parameter.type != AnimatorControllerParameterType.Trigger || containsMotion(parameter.name)) { newController.AddParameter(parameter.name, parameter.type); } else { EditorLogger.Log("忽略参数 {0}", parameter.name); } } //state AnimatorStateMachine newStateMachine = newController.layers[0].stateMachine; AnimatorStateMachine originStateMachine = originController.layers[0].stateMachine; newStateMachine.entryPosition = originStateMachine.entryPosition; newStateMachine.anyStatePosition = originStateMachine.anyStatePosition; newStateMachine.exitPosition = originStateMachine.exitPosition; foreach (ChildAnimatorState cstate in originStateMachine.states) { var statename = cstate.state.name; if (containsMotion(statename)) { var newState = newStateMachine.AddState(statename, cstate.position); newState.motion = motions[statename]; foreach (StateMachineBehaviour behaviour in cstate.state.behaviours) { newState.AddStateMachineBehaviour(behaviour.GetType()); } } else { EditorLogger.Log("忽略状态 {0}", statename); } } newStateMachine.defaultState = findState(originStateMachine.defaultState.name, newStateMachine); //transition foreach (ChildAnimatorState originChildState in originStateMachine.states) { AnimatorState newState = findState(originChildState.state.name, newStateMachine); if (newState != null) { foreach (AnimatorStateTransition originTransition in originChildState.state.transitions) { AnimatorState destState = findState(originTransition.destinationState.name, newStateMachine); if (destState != null) { var newTransition = newState.AddTransition(destState); copyTransition(originTransition, newTransition); } } } } foreach (AnimatorStateTransition anyTransition in originStateMachine.anyStateTransitions) { AnimatorState destState = findState(anyTransition.destinationState.name, newStateMachine); if (destState != null) { var newTransition = newStateMachine.AddAnyStateTransition(destState); copyTransition(anyTransition, newTransition); } } }
private void Change(bool change) { var t = gameObject.transform; var localPosition = t.localPosition; var localRotation = t.localRotation; var localScale = t.localScale; Undo.RecordObject(this, "Change Animator Controller"); Undo.RecordObject(animatorCache, "Change Animator Controller"); if (change) { Assert.IsFalse(changed); animatorCache.hideFlags |= HideFlags.NotEditable; originalAnimatorApplyRootMotion = animatorCache.applyRootMotion; originalAnimatorUpdateMode = animatorCache.updateMode; originalAnimatorCullingMode = animatorCache.cullingMode; animatorCache.applyRootMotion = false; animatorCache.updateMode = AnimatorUpdateMode.Normal; animatorCache.cullingMode = AnimatorCullingMode.AlwaysAnimate; #region AnimatorController { originalRuntimeAnimatorController = animatorCache.runtimeAnimatorController; tmpAnimatorController = new UnityEditor.Animations.AnimatorController(); tmpAnimatorController.name = "Very Animation Temporary Controller"; tmpAnimatorController.hideFlags |= HideFlags.HideAndDontSave; { tmpAnimatorController.AddLayer("Very Animation Layer"); layers = tmpAnimatorController.layers; foreach (var layer in layers) { layer.iKPass = true; var stateMachine = layer.stateMachine; stateMachine.hideFlags |= HideFlags.HideAndDontSave; { state = stateMachine.AddState("Animation"); state.hideFlags |= HideFlags.HideAndDontSave; stateNameHash = state.nameHash; } layer.stateMachine = stateMachine; } tmpAnimatorController.layers = layers; } UnityEditor.Animations.AnimatorController.SetAnimatorController(animatorCache, tmpAnimatorController); } #endregion changed = true; } else { Assert.IsTrue(changed); animatorCache.hideFlags &= ~HideFlags.NotEditable; animatorCache.applyRootMotion = originalAnimatorApplyRootMotion; animatorCache.updateMode = originalAnimatorUpdateMode; animatorCache.cullingMode = originalAnimatorCullingMode; #region AnimatorController { { var layerCount = tmpAnimatorController.layers.Length; for (int i = 0; i < layerCount; i++) { tmpAnimatorController.RemoveLayer(0); } } DestroyImmediate(tmpAnimatorController); tmpAnimatorController = null; animatorCache.runtimeAnimatorController = originalRuntimeAnimatorController; } #endregion originalRuntimeAnimatorController = null; changed = false; } //Cause unknown. It does not allow initialization. { t.localPosition = localPosition; t.localRotation = localRotation; t.localScale = localScale; } }
private void CreateTransitionWhenActivityIsOutOfBounds(AnimatorStateMachine machine, AnimatorState defaultState) { var transition = machine.AddAnyStateTransition(defaultState); SharedLayerUtils.SetupDefaultTransition(transition); foreach (var layer in _comboLayers) { transition.AddCondition(AnimatorConditionMode.NotEqual, layer.stageValue, _activityStageName); } }
private static void ReverseClip(AnimationClip clip, Animator[] animators)//List<AnimatorController> animConts { AnimationClip originalClip = clip; string directoryPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(clip)); //Selection.activeObject string fileName = Path.GetFileName(AssetDatabase.GetAssetPath(clip)); string fileExtension = Path.GetExtension(AssetDatabase.GetAssetPath(clip)); fileName = fileName.Split('.')[0]; string copiedFilePath = directoryPath + Path.DirectorySeparatorChar + fileName + "_Reversed" + fileExtension; AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(clip), copiedFilePath); clip = (AnimationClip)AssetDatabase.LoadAssetAtPath(copiedFilePath, typeof(AnimationClip)); if (clip == null) { return; } float clipLength = clip.length; var curves = AnimationUtility.GetCurveBindings(clip); foreach (EditorCurveBinding binding in curves) { var animCurve = AnimationUtility.GetEditorCurve(clip, binding); var keys = animCurve.keys; int keyCount = keys.Length; for (int i = 0; i < keyCount; i++) { Keyframe K = keys[i]; K.time = clipLength - K.time; var tmp = -K.inTangent; K.inTangent = -K.outTangent; K.outTangent = tmp; keys[i] = K; } animCurve.keys = keys; clip.SetCurve(binding.path, binding.type, binding.propertyName, animCurve); } var events = AnimationUtility.GetAnimationEvents(clip); if (events.Length > 0) { for (int i = 0; i < events.Length; i++) { events[i].time = clipLength - events[i].time; } AnimationUtility.SetAnimationEvents(clip, events); } foreach (Animator anim in animators) { AnimationClip[] clips = AnimationUtility.GetAnimationClips(anim.gameObject); bool foundClip = false; foreach (AnimationClip c in clips) { if (c == originalClip) { foundClip = true; break; } } if (foundClip) { Debug.Log("Found the animator containing the original clip that was reversed, adding new clip to its state machine..."); AnimatorController controller = UnityEditor.AssetDatabase.LoadAssetAtPath <UnityEditor.Animations.AnimatorController>(UnityEditor.AssetDatabase.GetAssetPath(anim.runtimeAnimatorController)); AnimatorStateMachine asm = controller.layers[0].stateMachine; AnimatorState animState = asm.AddState(clip.name); animState.motion = clip; } } }
private void Bake() { if (audioClipToBake.Count == 0) { EditorUtility.DisplayDialog("No AudioClip found", "You have not select a folder containing AudioClip. Please first specify a valid folder.", "OK"); } else { int animDataCount = 0; for (int i = 0; i < propertyNames.Length; ++i) { if (!string.IsNullOrEmpty(propertyNames[i])) { ++animDataCount; } else { break; } } if (animDataCount < currentVowels.Length) { EditorUtility.DisplayDialog("Incomplete animation data", "There is incomplete animation data. Please make sure you have filled all required data in the Animation Property Setting.", "OK"); } else { string path = ""; while (true) { path = EditorUtility.SaveFolderPanel("Save generated Animator to...", Application.dataPath, ""); if (path.IndexOf(Application.dataPath, 0) == 0) { path = path.Substring(Application.dataPath.Length - "Assets".Length); AnimatorController generatedAnimator = AnimatorController.CreateAnimatorControllerAtPath(path + "/" + animatorName + ".controller"); AnimatorStateMachine stateMachine = generatedAnimator.layers[0].stateMachine; if (AssetDatabase.IsValidFolder(path + "/GeneratedClips") == false) { AssetDatabase.CreateFolder(path, "GeneratedClips"); } LipSyncOfflineRecognizer recognizer = new LipSyncOfflineRecognizer(recognizerLanguage, amplitudeThreshold, windowSize, shiftStepSize); Dictionary <string, int> vowelToIndexDict = new Dictionary <string, int>(); for (int i = 0; i < currentVowels.Length; ++i) { vowelToIndexDict[currentVowels[i]] = i; } List <AnimationClip> tempClipList = new List <AnimationClip>(audioClipToBake.Count); for (int j = 0; j < audioClipToBake.Count; ++j) { AnimationClip clip = new AnimationClip(); AnimationCurve[] curveArray = new AnimationCurve[currentVowels.Length]; for (int jj = 0; jj < currentVowels.Length; ++jj) { curveArray[jj] = new AnimationCurve(); } float[] targetBlendValues = new float[currentVowels.Length]; float[] currentBlendValues = new float[currentVowels.Length]; string[] recognizeResult = recognizer.RecognizeAllByAudioClip(audioClipToBake[j]); float timeUnit = 1024.0f * (1.0f / (float)audioClipToBake[j].frequency); float blendValuesSum = 0.0f; for (int k = 0; k < recognizeResult.Length; ++k) { for (int kk = 0; kk < currentVowels.Length; ++kk) { targetBlendValues[kk] = 0; } if (recognizeResult[k] != null) { targetBlendValues[vowelToIndexDict[recognizeResult[k]]] = 1.0f; } blendValuesSum = 0.0f; for (int kk = 0; kk < currentVowels.Length; ++kk) { blendValuesSum += currentBlendValues[kk]; } for (int kk = 0; kk < currentVowels.Length; ++kk) { currentBlendValues[kk] = Mathf.MoveTowards(currentBlendValues[kk], targetBlendValues[kk], moveTowardsSpeed * timeUnit); Keyframe keyframe = new Keyframe(timeUnit * k, Mathf.Lerp(propertyMinValue, propertyMaxValue, currentBlendValues[kk])); curveArray[kk].AddKey(keyframe); } } for (int jj = 0; jj < currentVowels.Length; ++jj) { Keyframe keyframe = new Keyframe(timeUnit * recognizeResult.Length, 0); curveArray[jj].AddKey(keyframe); } for (int l = 0; l < currentVowels.Length; ++l) { clip.SetCurve(targetRelativePath, typeof(SkinnedMeshRenderer), "blendShape." + propertyNames[l], curveArray[l]); } tempClipList.Add(clip); } for (int m = 0; m < tempClipList.Count; ++m) { AssetDatabase.CreateAsset(tempClipList[m], path + "/GeneratedClips/" + audioClipToBake[m].name + "_anim.anim"); AnimatorState state = stateMachine.AddState(audioClipToBake[m].name + "_anim"); state.motion = tempClipList[m]; } EditorUtility.DisplayDialog("Complete Baking", "LipSync baking is completed. Please check the specified folder for result.", "OK"); break; } else if (path.Length == 0) { break; } else { Debug.Log(path); EditorUtility.DisplayDialog("Invalid path", "This folder is not contained in the asset path. Please make sure you choose a folder inside the \"Assets\" folder.", "OK"); } } } } }
void CreateANewController() { var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath("Assets/" + animationControllerName + ".controller"); controller.AddParameter("Forwards", AnimatorControllerParameterType.Float); controller.AddParameter("Horizontal", AnimatorControllerParameterType.Float); controller.AddParameter("Crouching", AnimatorControllerParameterType.Bool); controller.AddParameter("Speed", AnimatorControllerParameterType.Float); controller.AddParameter("Engaging", AnimatorControllerParameterType.Bool); controller.AddParameter("Melee", AnimatorControllerParameterType.Trigger); controller.AddParameter("Reloading", AnimatorControllerParameterType.Trigger); controller.AddParameter("Fire", AnimatorControllerParameterType.Trigger); controller.AddParameter("Sprinting", AnimatorControllerParameterType.Bool); //LAYER 1/////////////////////////////////////////// //Add Outer States var baseStateMachine = controller.layers[0].stateMachine; //Set Move Tree //new BlendTree(); BlendTree moveTree = new BlendTree(); AnimatorState moveState = controller.CreateBlendTreeInController("Move", out moveTree, 0); //Add Transitions AnimatorState baseCrouching = null; if (crouchingAnimation) { baseCrouching = baseStateMachine.AddState("Crouch"); baseCrouching.motion = crouchingAnimation; //Move var moveToCrouchTranistion = moveState.AddTransition(baseCrouching, false); moveToCrouchTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Crouching"); var crouchToMoveTranistion = baseCrouching.AddTransition(moveState, false); crouchToMoveTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.IfNot, 0.25f, "Crouching"); } if (fullBodyMeleeAnimation && meleeAnimation) { var baseMelee = baseStateMachine.AddState("Melee"); baseMelee.motion = meleeAnimation; //Melee if (baseCrouching != null) { var crouchToMeleeTranistion = baseCrouching.AddTransition(baseMelee, false); crouchToMeleeTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Melee"); } //Move var moveToMeleeTranistion = moveState.AddTransition(baseMelee, false); moveToMeleeTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Melee"); baseMelee.AddTransition(moveState, true); } // if (sprintingAnimation) { var baseSprint = baseStateMachine.AddState("Sprint"); baseSprint.motion = sprintingAnimation; //Move var moveToSprintTranistion = moveState.AddTransition(baseSprint, false); moveToSprintTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Sprinting"); var sprintToMoveTranistion = baseSprint.AddTransition(moveState, false); sprintToMoveTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.IfNot, 0.25f, "Sprinting"); } //Set Parameters moveTree.blendType = BlendTreeType.FreeformDirectional2D; moveTree.blendParameter = "Horizontal"; moveTree.blendParameterY = "Forwards"; //Add Animations float walkThreshold = 0.5f; float runThreshold = 1.0f; moveTree.AddChild(idleAnimation, new Vector2(0.0f, 0.0f)); moveTree.AddChild(runForwardsAnimation, new Vector2(0.0f, runThreshold)); if (walkForwardsAnimation) { moveTree.AddChild(walkForwardsAnimation, new Vector2(0.0f, walkThreshold)); } moveTree.AddChild(runBackwardsAnimation, new Vector2(0.0f, -runThreshold)); if (walkBackwardsAnimation) { moveTree.AddChild(walkBackwardsAnimation, new Vector2(0.0f, -walkThreshold)); } moveTree.AddChild(runRightAnimation, new Vector2(runThreshold, 0.0f)); if (walkRightAnimation) { moveTree.AddChild(walkRightAnimation, new Vector2(walkThreshold, 0.0f)); } moveTree.AddChild(runLeftAnimation, new Vector2(-runThreshold, 0.0f)); if (walkLeftAnimation) { moveTree.AddChild(walkLeftAnimation, new Vector2(-walkThreshold, 0.0f)); } //////////////////////////////////////////////////// //Layer 2 //////////////////////////////////////////////////// controller.AddLayer("UpperBody"); var upperStateMachine = controller.layers[1].stateMachine; var upperAim = upperStateMachine.AddState("Aim"); upperAim.motion = aimingAnimation; BlendTree idleUpperTree = new BlendTree(); AnimatorState upperIdle = controller.CreateBlendTreeInController("Idle", out idleUpperTree, 1); idleUpperTree.blendParameter = "Speed"; idleUpperTree.AddChild(idleUpperAnim, 0.0f); if (walkUpperAnim) { idleUpperTree.AddChild(walkUpperAnim, 0.5f); } if (runUpperAnim) { idleUpperTree.AddChild(runUpperAnim, 1.0f); } //Idle Transitions var idleToAim = upperIdle.AddTransition(upperAim, false); idleToAim.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Engaging"); var aimToidle = upperAim.AddTransition(upperIdle, false); aimToidle.AddCondition(UnityEditor.Animations.AnimatorConditionMode.IfNot, 0.25f, "Engaging"); //Melee if (meleeAnimation) { AnimatorState upperMelee = upperStateMachine.AddState("Melee"); upperMelee.motion = meleeAnimation; var aimToMeleeTranistion = upperAim.AddTransition(upperMelee, false); aimToMeleeTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Melee"); upperMelee.AddTransition(upperAim, true); } if (sprintingAnimation) { var upperSprint = upperStateMachine.AddState("Sprint"); upperSprint.motion = sprintingAnimation; //Move var aimToSprintTranistion = upperAim.AddTransition(upperSprint, false); aimToSprintTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Sprinting"); var sprintToAimTranistion = upperSprint.AddTransition(upperAim, false); sprintToAimTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.IfNot, 0.25f, "Sprinting"); } //Reload if (reloadAnimation) { AnimatorState reloadAnim = upperStateMachine.AddState("Reload"); reloadAnim.motion = reloadAnimation; var aimToReloadTranistion = upperAim.AddTransition(reloadAnim, false); aimToReloadTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Reloading"); reloadAnim.AddTransition(upperAim, true); } //Fire if (fireAnimation) { AnimatorState fireAnim = upperStateMachine.AddState("Fire"); fireAnim.motion = fireAnimation; var aimToFireTranistion = upperAim.AddTransition(fireAnim, false); aimToFireTranistion.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0.25f, "Fire"); fireAnim.AddTransition(upperAim, true); } }
public static bool UpdateValues(bool showMessage = false) { string[] guids = AssetDatabase.FindAssets("t: AnimatorController"); List <Object> revertState = new List <Object>(); double startTime = EditorApplication.timeSinceStartup; int behavioursCount = 0; int animatorsCount = 0; bool error = false; float currentIndex = -1; int behaviourIndex = -1; int behaviourCurrentCount = 0; EditorUtility.ClearProgressBar(); foreach (string guid in guids) { currentIndex += 1; if (showMessage) { EditorUtility.DisplayProgressBar("Rebuild Runtime MLPAS Animator State SFX Values", "Rebuilding... Animator: " + currentIndex.ToString() + "/" + guids.Length.ToString() + (behaviourCurrentCount > 0 ? " | Behaviours: " + (behaviourIndex).ToString() : ""), currentIndex / guids.Length); } AnimatorController anim = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(AnimatorController)) as AnimatorController; if (anim != null) { animatorsCount += 1; MLPASAnimatorSFX[] behaviours = anim.GetBehaviours <MLPASAnimatorSFX>(); behaviourCurrentCount = behaviours.Length; behavioursCount += behaviourCurrentCount; for (int i = 0; i < behaviours.Length; i++) { behaviourIndex += 1; if (!behaviours[i].UpdateRuntimeValues()) { error = true; break; } else { StateMachineBehaviourContext[] context = AnimatorController.FindStateMachineBehaviourContext(behaviours[i] as StateMachineBehaviour); if (context != null && context.Length > 0) { AnimatorState state = (context[0].animatorObject as AnimatorState); AnimatorStateMachine stateMachine = (context[0].animatorObject as AnimatorStateMachine); if (state != null) { foreach (var st in state.transitions) { if (st.duration == 0) { st.duration = 0.0001f; } } } if (stateMachine != null) { foreach (var st in stateMachine.anyStateTransitions) { if (st.duration == 0) { st.duration = 0.0001f; } } } revertState.Add(context[0].animatorObject); } } } } if (error) { break; } } if (!error) { if (showMessage) { Debug.Log("Rebuild Runtime Animator State SFX Values for: <b>" + animatorsCount + " Animators</b> - <b>" + behavioursCount + " Behaviours</b>" + " | <b>Operation Completed!</b>"); } AlmenaraGames.Tools.MLPASConfig config = Resources.Load("MLPASConfig/MLPASConfig", typeof(AlmenaraGames.Tools.MLPASConfig)) as AlmenaraGames.Tools.MLPASConfig; if (config != null) { config.stateClipboardBuffer = new AlmenaraGames.MLPASAnimatorSFX.StateSFX[0]; } } else { foreach (var item in revertState) { AnimatorState state = (item as AnimatorState); AnimatorStateMachine stateMachine = (item as AnimatorStateMachine); if (state != null) { foreach (var st in state.transitions) { if (st.duration == 0) { st.duration = 0.0001f; } } } if (stateMachine != null) { foreach (var st in stateMachine.anyStateTransitions) { if (st.duration == 0) { st.duration = 0.0001f; } } } } Debug.LogError("Rebuild Runtime Animator State SFX Values | <b>Operation Failed!</b>"); } if (showMessage) { AssetDatabase.SaveAssets(); EditorUtility.ClearProgressBar(); } return(!error); }
public void PlayAction(AnimatorState state, Vector3 pos, int deep, bool isMove = false, AnimatorState layerstate = AnimatorState.Empty) { PlayAnimation(state, layerstate); if (m_tRoot != null) { if (isMove) { m_tRoot.localPosition = pos; } else { /*pos = m_tRoot.localPosition; * pos.z = s_DeepDistint * (deep ); * m_tRoot.localPosition = pos;*/ } } }
/// <summary> /// 播放动画 /// </summary> public virtual void PlayAnimation(AnimatorState state, AnimatorState layerstate = AnimatorState.Empty) { }
public void CreateSkin(Transform parent, int roleType, string roleName, AnimatorState aniState, bool isplayer) { m_Skin = new RoleSkin(); m_Skin.CreateSkin(parent, roleType, roleName, aniState, isplayer); }
public void TraverseStateMachine(ref AnimatorStateMachine machine) { bool machineExist; var machineInfo = controllerInfo.machines.AddObject(machine, out machineExist); var stateMachinesPositionInfo = controllerInfo.stateMachinesPositionInfo.AddObject(machine, out machineExist); if (machineExist) { return; } var stateMachinesPositionInfoJSON = stateMachinesPositionInfo.Value; stateMachinesPositionInfoJSON.AddField("name", machine.name); JSONObject entryPosition = new JSONObject(JSONObject.Type.ARRAY); entryPosition.Add(machine.entryPosition.x); entryPosition.Add(machine.entryPosition.y); stateMachinesPositionInfoJSON.AddField("entryPosition", entryPosition); JSONObject exitPosition = new JSONObject(JSONObject.Type.ARRAY); exitPosition.Add(machine.exitPosition.x); exitPosition.Add(machine.exitPosition.y); stateMachinesPositionInfoJSON.AddField("exitPosition", exitPosition); JSONObject anyStatePosition = new JSONObject(JSONObject.Type.ARRAY); anyStatePosition.Add(machine.anyStatePosition.x); anyStatePosition.Add(machine.anyStatePosition.y); stateMachinesPositionInfoJSON.AddField("anyStatePosition", anyStatePosition); var machineJSON = machineInfo.Value; machineJSON.AddField("name", machine.name); if (!machine.defaultState) { machineJSON.AddField("defaultState", new JSONObject(JSONObject.Type.NULL)); } else { var defaultState = machine.defaultState; machineJSON.AddField("defaultState", HandleState(ref defaultState)); } JSONObject anyStateTransitions = new JSONObject(JSONObject.Type.ARRAY); for (int i = 0; i < machine.anyStateTransitions.Length; i++) { AnimatorStateTransition trans = machine.anyStateTransitions[i]; anyStateTransitions.Add(HandleStateTransition("any", ref trans)); } machineJSON.AddField("anyStateTransitions", anyStateTransitions); JSONObject statesJSON = new JSONObject(JSONObject.Type.ARRAY); ChildAnimatorState[] states = machine.states; for (int i = 0; i < states.Length; i++) { AnimatorState state = states[i].state; statesJSON.Add(HandleState(ref state)); } machineJSON.AddField("states", statesJSON); ChildAnimatorStateMachine[] subMachines = machine.stateMachines; for (int i = 0; i < subMachines.Length; i++) { AnimatorStateMachine subMachine = subMachines[i].stateMachine; TraverseStateMachine(ref subMachine); } }
public void SetTransition(AnimatorStateTransition transition, AnimatorState sourceState, AnimatorState destinationState, AnimatorControllerLayer srcLayer, Animator previewObject) { this.m_RefSrcState = sourceState; this.m_RefDstState = destinationState; TransitionInfo info = new TransitionInfo(); info.Set(transition, sourceState, destinationState); if (this.MustResample(info)) { this.ResampleTransition(transition, srcLayer.avatarMask, info, previewObject); } }
private void CreateThumbUpStates(AnimatorController animator, int layerIndex, HandClips clips) { AnimatorState thumbupState = animator.AddMotion(clips.thumbUp, layerIndex); animator.layers[layerIndex].stateMachine.defaultState = thumbupState; }
/* Create AnimationController when imports */ static void CreateController(string path, AnimationClip[] clips) { // Creates the controller AnimatorController controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(path); var rootStateMachine = controller.layers[0].stateMachine; AnimatorState idleState = rootStateMachine.AddState("Idle"); idleState.motion = clips[0]; // Beta/test@walking idleState.AddExitTransition(idleState); // Add parameters controller.AddParameter("TransitionNow", AnimatorControllerParameterType.Trigger); controller.AddParameter("Reset", AnimatorControllerParameterType.Trigger); controller.AddParameter("GotoB1", AnimatorControllerParameterType.Trigger); controller.AddParameter("GotoC", AnimatorControllerParameterType.Trigger); // Add StateMachines var rootStateMachine = controller.layers[0].stateMachine; var stateMachineA = rootStateMachine.AddStateMachine("smA"); var stateMachineB = rootStateMachine.AddStateMachine("smB"); var stateMachineC = stateMachineB.AddStateMachine("smC"); // Add States var stateA1 = stateMachineA.AddState("stateA1"); var stateB1 = stateMachineB.AddState("stateB1"); var stateB2 = stateMachineB.AddState("stateB2"); stateMachineC.AddState("stateC1"); // Blend Tree ? var stateC2 = stateMachineC.AddState("stateC2"); // don’t add an entry transition, should entry to state by default // Add Transitions var exitTransition = stateA1.AddExitTransition(); exitTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "TransitionNow"); exitTransition.duration = 0; var resetTransition = stateMachineA.AddAnyStateTransition(stateA1); resetTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Reset"); resetTransition.duration = 0; var transitionB1 = stateMachineB.AddEntryTransition(stateB1); transitionB1.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "GotoB1"); stateMachineB.AddEntryTransition(stateB2); stateMachineC.defaultState = stateC2; var exitTransitionC2 = stateC2.AddExitTransition(); exitTransitionC2.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "TransitionNow"); exitTransitionC2.duration = 0; var stateMachineTransition = rootStateMachine.AddStateMachineTransition(stateMachineA, stateMachineC); stateMachineTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "GotoC"); rootStateMachine.AddStateMachineTransition(stateMachineA, stateMachineB); }
public void clear() { m_anyCondList.Clear(); m_animatorState = null; }
public void EnteredState(int stateHash) { State = StateFor(stateHash); StateEntered?.Invoke(State); }
private void InitController() { gameObject = dg_get_PreviewObject(); if (gameObject == null) { return; } var originalGameObject = uAvatarPreviewSelection.GetPreview(dg_get_animationClipType()); animator = dg_get_Animator(); animation = gameObject.GetComponent <Animation>(); if (originalGameObject != null) { transformPoseSave = new TransformPoseSave(originalGameObject); transformPoseSave.SetRootTransform(gameObject.transform.localPosition, originalGameObject.transform.localRotation, originalGameObject.transform.localScale); transformPoseSave.ChangeTransforms(gameObject); } else { transformPoseSave = new TransformPoseSave(gameObject); } blendShapeWeightSave = new BlendShapeWeightSave(gameObject); var clip = dg_get_m_SourcePreviewMotion(instance); if (clip.legacy || instance == null || !((UnityEngine.Object)animator != (UnityEngine.Object)null)) { if (animation != null) { animation.enabled = false; //If vaw.animation.enabled, it is not updated during execution. bug? } } else { if (m_Controller == null) { m_Controller = new UnityEditor.Animations.AnimatorController(); m_Controller.name = "Avatar Preview AnimatorController"; m_Controller.hideFlags |= HideFlags.HideAndDontSave; uAnimatorController.SetPushUndo(m_Controller, false); m_Controller.AddLayer("preview"); m_StateMachine = m_Controller.layers[0].stateMachine; uAnimatorStateMachine.SetPushUndo(m_StateMachine, false); m_StateMachine.hideFlags |= HideFlags.HideAndDontSave; } if (m_State == null) { m_State = m_StateMachine.AddState("preview"); uAnimatorState.SetPushUndo(m_State, false); m_State.motion = (Motion)clip; m_State.iKOnFeet = dg_get_ShowIKOnFeetButton() && dg_get_IKOnFeet(); m_State.hideFlags |= HideFlags.HideAndDontSave; } UnityEditor.Animations.AnimatorController.SetAnimatorController(animator, this.m_Controller); animator.applyRootMotion = EditorPrefs.GetBool(EditorPrefsApplyRootMotion, false); } dg_set_ShowIKOnFeetButton(animator != null && animator.isHuman && clip.isHumanMotion); #if !UNITY_2017_3_OR_NEWER mode2D = EditorPrefs.GetBool(EditorPrefs2D, false); #endif SetTime(uTimeControl.currentTime); ForceUpdate(); }
private void CreateController() { if (((this.m_Controller == null) && (this.m_AvatarPreview != null)) && ((this.m_AvatarPreview.Animator != null) && (this.m_RefTransition != null))) { this.m_LayerIndex = 0; this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.AddLayer("preview"); bool flag = true; if (this.m_LayerMask != null) { int humanoidBodyPartCount = this.m_LayerMask.humanoidBodyPartCount; for (int i = 0; (i < humanoidBodyPartCount) && flag; i++) { if (!this.m_LayerMask.GetHumanoidBodyPartActive(i)) { flag = false; } } if (!flag) { this.m_Controller.AddLayer("Additionnal"); this.m_LayerIndex++; AnimatorControllerLayer[] layers = this.m_Controller.layers; layers[this.m_LayerIndex].avatarMask = this.m_LayerMask; this.m_Controller.layers = layers; } } this.m_StateMachine = this.m_Controller.layers[this.m_LayerIndex].stateMachine; this.m_StateMachine.pushUndo = false; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; this.m_SrcMotion = this.m_RefSrcState.motion; this.m_DstMotion = this.m_RefDstState.motion; this.m_ParameterMinMax.Clear(); if ((this.m_SrcMotion != null) && (this.m_SrcMotion is BlendTree)) { BlendTree srcMotion = this.m_SrcMotion as BlendTree; for (int j = 0; j < srcMotion.recursiveBlendParameterCount; j++) { string recursiveBlendParameter = srcMotion.GetRecursiveBlendParameter(j); if (this.m_Controller.IndexOfParameter(recursiveBlendParameter) == -1) { this.m_Controller.AddParameter(recursiveBlendParameter, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(srcMotion.GetRecursiveBlendParameterMin(j), srcMotion.GetRecursiveBlendParameterMax(j))); } } } if ((this.m_DstMotion != null) && (this.m_DstMotion is BlendTree)) { BlendTree dstMotion = this.m_DstMotion as BlendTree; for (int k = 0; k < dstMotion.recursiveBlendParameterCount; k++) { string name = dstMotion.GetRecursiveBlendParameter(k); int num5 = this.m_Controller.IndexOfParameter(name); if (num5 == -1) { this.m_Controller.AddParameter(name, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(dstMotion.GetRecursiveBlendParameterMin(k), dstMotion.GetRecursiveBlendParameterMax(k))); } else { Vector2 vector = this.m_ParameterMinMax[num5]; Vector2 vector2 = this.m_ParameterMinMax[num5]; this.m_ParameterMinMax[num5] = new Vector2(Mathf.Min(dstMotion.GetRecursiveBlendParameterMin(k), vector[0]), Mathf.Max(dstMotion.GetRecursiveBlendParameterMax(k), vector2[1])); } } } this.m_SrcState = this.m_StateMachine.AddState(this.m_RefSrcState.name); this.m_SrcState.pushUndo = false; this.m_SrcState.hideFlags = HideFlags.HideAndDontSave; this.m_DstState = this.m_StateMachine.AddState(this.m_RefDstState.name); this.m_DstState.pushUndo = false; this.m_DstState.hideFlags = HideFlags.HideAndDontSave; this.CopyStateForPreview(this.m_RefSrcState, ref this.m_SrcState); this.CopyStateForPreview(this.m_RefDstState, ref this.m_DstState); this.m_Transition = this.m_SrcState.AddTransition(this.m_DstState, true); this.m_Transition.pushUndo = false; this.m_Transition.hideFlags = HideFlags.DontSave; this.CopyTransitionForPreview(this.m_RefTransition, ref this.m_Transition); this.DisableIKOnFeetIfNeeded(); AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_Controller.OnAnimatorControllerDirty = (System.Action) Delegate.Combine(this.m_Controller.OnAnimatorControllerDirty, new System.Action(this.ControllerDirty)); } }
private void SetMotion(AnimatorState state, int layerIndex, Motion motion) { AnimatorControllerLayer[] layers = this.m_Controller.layers; state.motion = motion; this.m_Controller.layers = layers; }
/// <summary> /// Update the avatar of a UMA character. /// </summary> /// <param name="umaData">UMA data.</param> public virtual void UpdateAvatar(UMAData umaData) { if (umaData) { AnimatorState snapshot = new AnimatorState(); if (umaData.animationController != null) { var animator = umaData.animator; if (animator != null) { if (umaData.animationController == animator.runtimeAnimatorController) { snapshot = new AnimatorState(); snapshot.SaveAnimatorState(animator); } Avatar avatar = animator.avatar; Object.DestroyImmediate(animator); Object.Destroy(avatar); } var umaTransform = umaData.transform; var oldParent = umaTransform.parent; var originalRot = umaTransform.localRotation; var originalPos = umaTransform.localPosition; umaTransform.parent = null; umaTransform.localRotation = Quaternion.identity; umaTransform.localPosition = Vector3.zero; animator = CreateAnimator(umaData, umaData.umaRecipe.raceData.TPose, umaData.animationController); umaData.animator = animator; umaTransform.parent = oldParent; umaTransform.localRotation = originalRot; umaTransform.localPosition = originalPos; snapshot.RestoreAnimatorState(animator); } } }
public void SetTransition(AnimatorStateTransition transition, AnimatorState sourceState, AnimatorState destinationState, AnimatorControllerLayer srcLayer, Animator previewObject) { this.m_RefSrcState = sourceState; this.m_RefDstState = destinationState; TransitionPreview.TransitionInfo transitionInfo = new TransitionPreview.TransitionInfo(); transitionInfo.Set(transition, sourceState, destinationState); if (this.MustResample(transitionInfo)) { this.ResampleTransition(transition, srcLayer.avatarMask, transitionInfo, previewObject); } }
private void ClearStateMachine() { if ((UnityEngine.Object) this.m_Animator != (UnityEngine.Object) null) AnimatorController.SetAnimatorController(this.m_Animator, (AnimatorController) null); if ((UnityEngine.Object) this.m_Controller != (UnityEngine.Object) null) this.m_Controller.OnAnimatorControllerDirty -= new System.Action(this.ControllerDirty); UnityEngine.Object.DestroyImmediate((UnityEngine.Object) this.m_Controller); UnityEngine.Object.DestroyImmediate((UnityEngine.Object) this.m_State); this.m_StateMachine = (AnimatorStateMachine) null; this.m_Controller = (AnimatorController) null; this.m_State = (AnimatorState) null; }
public override void OnInspectorGUI() { if (target is UIObject obj && !obj.useController) { if (targets.Length == 1) { Animator animator = (target as UIObject).GetComponent <Animator>(); if (animator == null || animator.runtimeAnimatorController == null) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("必须有Animator和AnimatorController才能使用Controller"); if (GUILayout.Button("创建Controller")) { if (animator == null) { animator = (target as UIObject).gameObject.AddComponent <Animator>(); } string controllerPath = EditorUtility.SaveFilePanel("保存动画控制器", Application.dataPath, (target as UIObject).gameObject.name + "_Controller", "controller"); controllerPath = controllerPath.Replace(Environment.CurrentDirectory.Replace('\\', '/') + "/", string.Empty); AnimatorController controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath); animator.runtimeAnimatorController = controller; } EditorGUILayout.EndHorizontal(); } else if (animator.runtimeAnimatorController is AnimatorController controller) { AnimatorControllerLayer removeLayer = null; AnimatorControllerLayer rebuildLayer = null; string controllerPath = AssetDatabase.GetAssetPath(controller); string controllerDir = Path.GetDirectoryName(controllerPath); foreach (AnimatorControllerLayer layer in controller.layers) { Match m = Regex.Match(layer.name, @"(?<name>\w+)Controller"); if (m.Success) { string controllerName = m.Groups["name"].Value; if (!controllerFoldDic.ContainsKey(controllerName)) { controllerFoldDic.Add(controllerName, false); } layer.defaultWeight = 1; EditorGUILayout.BeginHorizontal(); //展开Controller controllerFoldDic[controllerName] = EditorGUILayout.Foldout(controllerFoldDic[controllerName], controllerName); if (EditorApplication.isPlaying && targets.Length == 1) { //Controller当前状态 string currentStateName = (target as UIObject).getController(controllerName, layer.stateMachine.states.Select(s => s.state.name).ToArray()); EditorGUILayout.LabelField(currentStateName, GUILayout.Width(100)); // Debug.Log(currentStateName, target); } else if (layer.stateMachine != null && layer.stateMachine.states.Length > 0) { SerializedProperty initStatesProp = serializedObject.FindProperty("_initStates"); int propIndex = -1; for (int i = 0; i < initStatesProp.arraySize; i++) { if (initStatesProp.GetArrayElementAtIndex(i).stringValue.Contains(controllerName)) { propIndex = i; break; } } if (propIndex < 0) { initStatesProp.arraySize++; propIndex = initStatesProp.arraySize - 1; } string initState = initStatesProp.GetArrayElementAtIndex(propIndex).stringValue.Replace(controllerName + "/", null); int stateIndex = Array.FindIndex(layer.stateMachine.states, s => s.state.name == initState); if (stateIndex < 0) { stateIndex = 0; } int newStateIndex = EditorGUILayout.Popup(stateIndex, layer.stateMachine.states.Select(s => s.state.name).ToArray(), GUILayout.Width(100)); if (newStateIndex != stateIndex) { animator.enabled = true; animator.speed = 0; animator.Play(layer.stateMachine.states[newStateIndex].state.name, animator.GetLayerIndex(controllerName + "Controller")); animator.Update(Time.deltaTime); } initStatesProp.GetArrayElementAtIndex(propIndex).stringValue = controllerName + "/" + layer.stateMachine.states[newStateIndex].state.name; } //删除Controller if (GUILayout.Button("-", GUILayout.Width(20))) { removeLayer = layer; } EditorGUILayout.EndHorizontal(); //Controller内容绘制 if (controllerFoldDic[controllerName]) { EditorGUI.indentLevel++; AnimatorState removeState = null; //状态绘制 if (layer.stateMachine == null) { rebuildLayer = layer; } else { foreach (ChildAnimatorState state in layer.stateMachine.states) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(state.state.name, ""); if (EditorApplication.isPlaying && GUILayout.Button(">", GUILayout.Width(20))) { (target as UIObject).setController(controllerName, state.state.name); } if (GUILayout.Button("-", GUILayout.Width(20))) { removeState = state.state; } EditorGUILayout.EndHorizontal(); } if (removeState != null) { if (removeState.motion is AnimationClip removeClip) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(removeClip)); } layer.stateMachine.RemoveState(removeState); } EditorGUILayout.BeginHorizontal(); //新建状态 if (!controllerNewStateDic.ContainsKey(controllerName)) { controllerNewStateDic.Add(controllerName, null); } controllerNewStateDic[controllerName] = EditorGUILayout.TextField(controllerNewStateDic[controllerName]); if (GUILayout.Button("AddState")) { if (layer.stateMachine.states.Any(s => s.state.name == controllerNewStateDic[controllerName])) { Debug.LogError(controllerName + "中已经存在同名的状态,无法添加" + controllerNewStateDic[controllerName]); } else if (string.IsNullOrEmpty(controllerNewStateDic[controllerName])) { Debug.LogError("Controller状态名称不能为空"); } else { if (Directory.Exists(controllerDir)) { AnimationClip newClip = new AnimationClip(); AssetDatabase.CreateAsset(newClip, controllerDir + "/" + controllerName + "_" + controllerNewStateDic[controllerName] + ".anim"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); AnimatorState newState = new AnimatorState() { name = controllerNewStateDic[controllerName], motion = newClip }; layer.stateMachine.AddState(newState, new Vector3(250, layer.stateMachine.states.Length * 50)); EditorUtility.SetDirty(controller); AssetDatabase.AddObjectToAsset(newState, controller); AssetDatabase.SaveAssets(); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller)); } else { Debug.LogError("文件夹" + controllerDir + "不存在", target); } } controllerNewStateDic.Remove(controllerName); } EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } } } //删除Controller的实际处理 if (removeLayer != null) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(controller) + "/" + removeLayer.stateMachine.name); controller.RemoveLayer(Array.FindIndex(controller.layers, l => l.name == removeLayer.name)); EditorUtility.SetDirty(controller); AssetDatabase.SaveAssets(); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller)); } //stateMachine的Layer丢失了似乎重新新建它是没用的。那就只能试试看重建它了。 if (rebuildLayer != null) { string controllerName = rebuildLayer.name.Replace("Controller", string.Empty); controller.RemoveLayer(Array.FindIndex(controller.layers, l => l.name == rebuildLayer.name)); AnimatorControllerLayer layer = new AnimatorControllerLayer() { name = controllerName + "Controller", defaultWeight = 1, stateMachine = new AnimatorStateMachine() { name = controllerName + "Controller" } }; foreach (string animPath in Directory.GetFiles(controllerDir, "*.anim") .Select(s => s.Replace('\\', '/').Replace(Environment.CurrentDirectory.Replace('\\', '/') + "/", string.Empty))) { AnimationClip clip = AssetDatabase.LoadAssetAtPath <AnimationClip>(animPath); Match m = Regex.Match(clip.name, @"(?<controller>\w+)_(?<state>\w+)"); if (m.Success && m.Groups["controller"].Value == controllerName) { string stateName = m.Groups["state"].Value; AnimatorState newState = new AnimatorState() { name = stateName, motion = clip }; layer.stateMachine.AddState(newState, new Vector3(250, layer.stateMachine.states.Length * 50)); } } controller.AddLayer(layer); EditorUtility.SetDirty(controller); AssetDatabase.AddObjectToAsset(layer.stateMachine, controller); AssetDatabase.SaveAssets(); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller)); } //新建Controller EditorGUILayout.BeginHorizontal(); newControllerName = EditorGUILayout.TextField(newControllerName); if (GUILayout.Button("AddController")) { if (controller.layers.Any(l => l.name == newControllerName + "Controller")) { Debug.LogError("已经存在同名Controller,无法添加" + newControllerName); } else if (string.IsNullOrEmpty(newControllerName)) { Debug.LogError("Controller名称不能为空"); } else { AnimatorControllerLayer newLayer = new AnimatorControllerLayer { name = newControllerName + "Controller", defaultWeight = 1, stateMachine = new AnimatorStateMachine() }; controller.AddLayer(newLayer); EditorUtility.SetDirty(controller); AssetDatabase.AddObjectToAsset(newLayer.stateMachine, controller); AssetDatabase.SaveAssets(); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller)); } newControllerName = null; } EditorGUILayout.EndHorizontal(); serializedObject.ApplyModifiedProperties(); } } else { EditorGUILayout.LabelField("无法同时编辑多个物体的动画控制器"); } } base.OnInspectorGUI();//Generated fields }
protected override void createAnimations(GAFTimelineData _Timeline, AnimatorController _AnimatorController, string _AnimationsPath) { #if !UNITY_5 var layer = _AnimatorController.GetLayer(0); var stateMachine = layer.stateMachine; var isNewStateMachine = stateMachine.stateCount == 0; var i = 0; foreach (var sequence in _Timeline.sequences) { int stateFoundIndex = -1; for (int stateIndex = 0; stateIndex < stateMachine.stateCount; ++stateIndex) { if (stateMachine.GetState(stateIndex).name == sequence.name) { stateFoundIndex = stateIndex; break; } } var clipName = _AnimatorController.name + "_" + sequence.name + ".anim"; var clip = AssetDatabase.LoadAssetAtPath(_AnimationsPath + clipName, typeof(AnimationClip)) as AnimationClip; if (clip == null) { clip = createAnimationClip(_Timeline, sequence, _AnimationsPath + clipName); } State state = null; if (stateFoundIndex >= 0) { state = stateMachine.GetState(stateFoundIndex); } else { state = stateMachine.AddState(sequence.name); state.position = new Vector3(0, 50f, 0f) * i; } state.SetAnimationClip(clip); if (isNewStateMachine) { if (sequence.name.ToLower() == "default") { stateMachine.defaultState = state; } } ++i; } #else var layer = _AnimatorController.layers[0]; var stateMachine = layer.stateMachine; var isNewStateMachine = stateMachine.states.Length == 0; var i = 0; foreach (var sequence in _Timeline.sequences) { int stateFoundIndex = -1; for (int stateIndex = 0; stateIndex < stateMachine.states.Length; ++stateIndex) { if (stateMachine.states[stateIndex].state.name == sequence.name) { stateFoundIndex = stateIndex; break; } } var clipName = _AnimatorController.name + "_" + sequence.name + ".anim"; var clip = AssetDatabase.LoadAssetAtPath(_AnimationsPath + clipName, typeof(AnimationClip)) as AnimationClip; if (clip == null) { clip = createAnimationClip(_Timeline, sequence, _AnimationsPath + clipName); } AnimatorState state = null; if (stateFoundIndex >= 0) { state = stateMachine.states[stateFoundIndex].state; } else { state = stateMachine.AddState(sequence.name, new Vector3(0, 50f, 0f) * i); } state.motion = clip; if (isNewStateMachine) { if (sequence.name.ToLower() == "default") { stateMachine.defaultState = state; } } ++i; } #endif // !UNITY_5 }
private static void createAC(string objPath, string objName, Dictionary <string, animCond> conds, List <animClip> lstInfo) { //查找混合树 List <animClip> blendInfo = new List <animClip>(); for (int i = 0; i < lstInfo.Count; i++) { if (lstInfo[i].blendIndex > 0) { blendInfo.Add(lstInfo[i]); } } int index = objPath.LastIndexOf("/"); string savePath = getAnimPathByName(objName, "ac"); string clipPath = getAnimPathByName(objName, "clip"); AnimatorController ac = AnimatorController.CreateAnimatorControllerAtPath(Path.Combine(savePath, objName + ".controller")); AnimatorControllerLayer layer = ac.layers[0]; //添加clip AnimatorStateMachine stateMachine = layer.stateMachine; string[] files = Directory.GetFiles(clipPath, "*anim"); Dictionary <string, Motion> dictClips = new Dictionary <string, Motion>(); for (int i = 0; i < files.Length; i++) { Motion cp = AssetDatabase.LoadAssetAtPath <Motion>(files[i]); if (cp != null) { dictClips.Add(cp.name, cp); } } AnimatorState animState = null; //先创建blendTree if (blendInfo.Count > 0) { if (!isExitParam(ac, "tree")) { ac.AddParameter("tree", AnimatorControllerParameterType.Float); } BlendTree btree = null; animState = ac.CreateBlendTreeInController(defaultAnim, out btree); btree.blendParameter = "tree"; for (int i = 0; i < blendInfo.Count; i++) { string cname = blendInfo[i].clipName; if (dictClips.ContainsKey(cname)) { btree.AddChild(dictClips[cname]); } } stateMachine.AddState(animState, new Vector2(600, -200)); stateMachine.defaultState = animState; } int startY = 0; int startX = 300; for (int i = 0; i < lstInfo.Count; i++) { if (lstInfo[i].blendIndex > 0) { continue; } string name = lstInfo[i].clipName; animState = stateMachine.AddState(name, new Vector2(startX, startY * 80)); animState.motion = dictClips[name]; startY++; } //连线 ChildAnimatorState[] states = stateMachine.states; for (int i = 0; i < states.Length; i++) { ChildAnimatorState currState = states[i]; string name = currState.state.name; if (conds.ContainsKey(name)) { animCond cond = conds[name]; string fromStateName = cond.fromState; if (fromStateName == "Any State") { AnimatorStateTransition trans = stateMachine.AddAnyStateTransition(currState.state); if (!isExitParam(ac, cond.fromCond)) { ac.AddParameter(cond.fromCond, AnimatorControllerParameterType.Trigger); } trans.AddCondition(AnimatorConditionMode.If, 0, cond.fromCond); } string toStateName = cond.toState; ChildAnimatorState toState = getState(states, toStateName); if (toState.state != null && name != defaultAnim) { AnimatorStateTransition trans = currState.state.AddTransition(toState.state); if (cond.toCond == "None") { trans.hasExitTime = false; } else if (cond.toCond == "Exit") { trans.hasExitTime = true; } else { if (!isExitParam(ac, cond.toCond)) { ac.AddParameter(cond.toCond, AnimatorControllerParameterType.Trigger); } trans.AddCondition(AnimatorConditionMode.If, 0, cond.toCond); } } } } ac.name = objName; //AssetDatabase.CreateAsset(ac, Path.Combine(savePath, objName + ".controller")); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); }
static public void GetBlendRule(int nRoleID, AnimatorState preState, AnimatorState nextState, ref AnimatorState blendSTate, ref float fBlendTime) { /*if (nRoleID == 102001) * { * if (preState == AnimatorState.Skill01 && nextState != AnimatorState.Skill01) * { * blendSTate = AnimatorState.JumpUp; * fBlendTime = 1.3f; * } * else if (preState == AnimatorState.JumpDown) * { * blendSTate = AnimatorState.Skill04; * fBlendTime = 0.6f; * } * else if (nextState == AnimatorState.NoSquash) * { * blendSTate = AnimatorState.SquashPeak; * fBlendTime = 0.9f; * } * * } * else * {*/ blendSTate = AnimatorState.Empty; fBlendTime = 0.0f; //} }
private void InitController() { if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) { if (this.m_Controller == null) { this.m_Controller = new UnityEditor.Animations.AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.AddLayer("preview"); this.m_StateMachine = this.m_Controller.layers[0].stateMachine; this.m_StateMachine.pushUndo = false; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; if (this.m_ClipInfo != null) { this.InitMask(); UnityEditor.Animations.AnimatorControllerLayer[] layers = this.m_Controller.layers; layers[0].avatarMask = this.m_Mask; this.m_Controller.layers = layers; } } if (this.m_State == null) { this.m_State = this.m_StateMachine.AddState("preview"); this.m_State.pushUndo = false; UnityEditor.Animations.AnimatorControllerLayer[] layers2 = this.m_Controller.layers; this.m_State.motion = this.m_Clip; this.m_Controller.layers = layers2; this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; this.m_State.hideFlags = HideFlags.HideAndDontSave; } UnityEditor.Animations.AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); if (UnityEditor.Animations.AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) { UnityEditor.Animations.AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); } } }
protected override void DoPreview() { this.Init(); AnimatorStateTransition targetObject = base.m_SerializedTransition.targetObject as AnimatorStateTransition; AnimatorState sourceState = this.GetSourceState((base.m_TransitionList == null) ? 0 : base.m_TransitionList.index); AnimatorState destinationState = targetObject.destinationState; EditorGUILayout.PropertyField(this.m_HasExitTime, styles.hasExitTime, new GUILayoutOption[0]); m_ShowSettings = EditorGUILayout.Foldout(m_ShowSettings, "Settings"); if (m_ShowSettings) { EditorGUI.indentLevel++; bool enabled = GUI.enabled; GUI.enabled = this.m_HasExitTime.boolValue; EditorGUILayout.PropertyField(this.m_ExitTime, styles.exitTime, new GUILayoutOption[0]); GUI.enabled = enabled; EditorGUILayout.PropertyField(this.m_HasFixedDuration, styles.hasFixedDuration, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Duration, !this.m_HasFixedDuration.boolValue ? styles.transitionDurationNormalized : styles.transitionDurationFixed, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Offset, styles.transitionOffset, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_InterruptionSource, styles.interruptionSource, new GUILayoutOption[0]); TransitionInterruptionSource enumValueIndex = (TransitionInterruptionSource)this.m_InterruptionSource.enumValueIndex; GUI.enabled = ((enumValueIndex == TransitionInterruptionSource.Source) || (enumValueIndex == TransitionInterruptionSource.SourceThenDestination)) || (enumValueIndex == TransitionInterruptionSource.DestinationThenSource); EditorGUILayout.PropertyField(this.m_OrderedInterruption, styles.orderedInterruption, new GUILayoutOption[0]); GUI.enabled = enabled; if ((sourceState == null) && (destinationState != null)) { EditorGUILayout.PropertyField(this.m_CanTransitionToSelf, new GUILayoutOption[0]); } EditorGUI.indentLevel--; } if (this.IsPreviewable()) { AnimatorStateMachine stateMachine = base.m_Controller.layers[base.m_LayerIndex].stateMachine; if (sourceState == null) { List <ChildAnimatorState> statesRecursive = stateMachine.statesRecursive; string[] displayedOptions = new string[statesRecursive.Count]; int num = 0; foreach (ChildAnimatorState state3 in statesRecursive) { displayedOptions[num++] = state3.state.name; } EditorGUILayout.Space(); this.m_AnyStateSourceIndex = EditorGUILayout.Popup("Preview source state", this.m_AnyStateSourceIndex, displayedOptions, new GUILayoutOption[0]); EditorGUILayout.Space(); ChildAnimatorState state4 = statesRecursive[this.m_AnyStateSourceIndex]; sourceState = state4.state; } if (destinationState == null) { if (this.m_DstStates.Count > 0) { string[] strArray2 = new string[this.m_DstStates.Count]; int num2 = 0; foreach (AnimatorState state5 in this.m_DstStates) { strArray2[num2++] = state5.name; } EditorGUILayout.Space(); this.m_DstStateIndex = EditorGUILayout.Popup("Preview destination state", this.m_DstStateIndex, strArray2, new GUILayoutOption[0]); if (this.m_DstStates.Count > this.m_DstStateIndex) { destinationState = this.m_DstStates[this.m_DstStateIndex]; } else { destinationState = null; } EditorGUILayout.Space(); } else { EditorGUILayout.HelpBox("Cannot preview transition, there is no destination state", MessageType.Warning, true); } } if ((sourceState != null) && (destinationState != null)) { this.m_TransitionPreview.SetTransition(targetObject, sourceState, destinationState, base.m_Controller.layers[base.m_LayerIndex], base.m_PreviewObject); this.m_TransitionPreview.DoTransitionPreview(); } } else { EditorGUILayout.HelpBox(this.m_InvalidTransitionMessage, MessageType.Warning, true); } }
private void CreateStateMachine() { if (avatarPreview == null || avatarPreview.Animator == null) return; if (controller == null) { controller = new AnimatorController(); controller.hideFlags = HideFlags.DontSave; controller.AddLayer("preview"); stateMachine = controller.layers[0].stateMachine; CreateParameters(); state = stateMachine.AddState("preview"); state.motion = previewedMotion; state.iKOnFeet = this.avatarPreview.IKOnFeet; state.hideFlags = HideFlags.DontSave; stateMachine.hideFlags = HideFlags.DontSave; AnimatorController.SetAnimatorController(avatarPreview.Animator, controller); controller.AppendOnAnimatorControllerDirtyCallback(this.ControllerDitry); controllerIsDitry = false; } if (AnimatorControllerExtension.GetEffectiveAnimatorController(avatarPreview.Animator) != this.controller) { AnimatorController.SetAnimatorController(avatarPreview.Animator, this.controller); } }
void ControllerBuild(HashSet <ClipIDPair> clips)//, int c) { { //if (clips == null) return; // Create the animator in the project AnimatorController controller = AnimatorController.CreateAnimatorControllerAtPath(saveDirectory + "AnimationsController.controller"); //add parameters AddParameters(controller); float t = Time.realtimeSinceStartup; { AnimatorControllerLayer[] layers = controller.layers; AnimatorControllerLayer layer = layers[0]; layer.iKPass = true; AnimatorStateMachine sm = layer.stateMachine; AnimatorState[] blendTrees = new AnimatorState[0]; if (usedLoopIDsPerLayer[0].Count > 0) { //make blend trees for looped animations (2 to smoothly transition between loops) blendTrees = new AnimatorState[2];//2]; for (int i = 0; i < 2; i++) { blendTrees[i] = AddBlendTree( controller, sm, 0, clips, CustomAnimator.loopNamesStrings[i], CustomAnimator.loopMirrorStrings[i], CustomAnimator.loopSpeedStrings[i], CustomAnimator.loopIndexStrings[i] ); } // blendTrees[i] = AddBlendTree(controller, 0, clips, CustomAnimator.sLoopNames[i], CustomAnimator.sLoopMirrors[i], CustomAnimator.sLoopSpeeds[i], c, CustomAnimator.sLoopIndicies[i]); // ConnectBlendTrees(0, blendTrees, 0); } // for (int i = 0; i < c; i++) // AddState(controller, sm, 0, clips[i], blendTrees); foreach (var c in clips) { AddState(0, controller, sm, 0, c, blendTrees); } controller.layers = layers; } Debug.Log("Time building layer 0: " + (Time.realtimeSinceStartup - t)); t = Time.realtimeSinceStartup; for (int l = 1; l < maxLayer + 1; l++) { controller.AddLayer("Layer" + l); AnimatorControllerLayer[] layers = controller.layers; AnimatorControllerLayer layer = layers[l]; layer.iKPass = true; layer.defaultWeight = 1.0f; AnimatorStateMachine sm = layer.stateMachine; bool anyLoops = usedLoopIDsPerLayer[l].Count > 0; AnimatorState[] blendTrees = new AnimatorState[anyLoops ? CustomAnimator.BLEND_TREES_PER_LAYER + 1 : 1]; // make the empty default state // AnimatorState state = sm.AddState(CustomAnimator.loopNamesStrings[l*3 + 0]); blendTrees[0] = sm.AddState("Blank");//CustomAnimator.loopNamesStrings[l*3 + 0]); blendTrees[0].motion = null; if (anyLoops) { for (int i = 0; i < CustomAnimator.BLEND_TREES_PER_LAYER; i++) { blendTrees[i + 1] = AddBlendTree( controller, sm, l, clips, CustomAnimator.loopNamesStrings[l * CustomAnimator.BLEND_TREES_PER_LAYER + (i)], CustomAnimator.loopMirrorStrings[l * CustomAnimator.BLEND_TREES_PER_LAYER + (i)], CustomAnimator.loopSpeedStrings[l * CustomAnimator.BLEND_TREES_PER_LAYER + (i)], //c, CustomAnimator.loopIndexStrings[l * CustomAnimator.BLEND_TREES_PER_LAYER + (i)] ); } // ConnectBlendTrees(-1, blendTrees, l); } // if (!upperLayersOnlyLoops) { // } // for (int i = 0; i < c; i++) // AddState(controller, sm, l, clips[i], blendTrees); foreach (var c in clips) { AddState(-1, controller, sm, l, c, blendTrees); } controller.layers = layers; } EditorUtility.SetDirty(controller); Debug.Log("Time building other layers: " + (Time.realtimeSinceStartup - t)); }
internal extern string GetDisplayNameStateSource(AnimatorState source);
public State(AnimatorState value) { this.value = value; this.stateNameLength = value.name.Length; this.motionNameLength = value.motion.name.Length; }
private void CreateController() { if (this.m_Controller == null && this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null && this.m_RefTransition != null) { this.m_LayerIndex = 0; this.m_Controller = new AnimatorController(); this.m_Controller.pushUndo = false; this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.AddLayer("preview"); bool flag = true; if (this.m_LayerMask != null) { int humanoidBodyPartCount = this.m_LayerMask.humanoidBodyPartCount; int num = 0; while (num < humanoidBodyPartCount && flag) { if (!this.m_LayerMask.GetHumanoidBodyPartActive(num)) { flag = false; } num++; } if (!flag) { this.m_Controller.AddLayer("Additionnal"); this.m_LayerIndex++; AnimatorControllerLayer[] layers = this.m_Controller.layers; layers[this.m_LayerIndex].avatarMask = this.m_LayerMask; this.m_Controller.layers = layers; } } this.m_StateMachine = this.m_Controller.layers[this.m_LayerIndex].stateMachine; this.m_StateMachine.pushUndo = false; this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; this.m_SrcMotion = this.m_RefSrcState.motion; this.m_DstMotion = this.m_RefDstState.motion; this.m_ParameterMinMax.Clear(); if (this.m_SrcMotion && this.m_SrcMotion is BlendTree) { BlendTree blendTree = this.m_SrcMotion as BlendTree; for (int i = 0; i < blendTree.recursiveBlendParameterCount; i++) { string recursiveBlendParameter = blendTree.GetRecursiveBlendParameter(i); if (this.m_Controller.IndexOfParameter(recursiveBlendParameter) == -1) { this.m_Controller.AddParameter(recursiveBlendParameter, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(blendTree.GetRecursiveBlendParameterMin(i), blendTree.GetRecursiveBlendParameterMax(i))); } } } if (this.m_DstMotion && this.m_DstMotion is BlendTree) { BlendTree blendTree2 = this.m_DstMotion as BlendTree; for (int j = 0; j < blendTree2.recursiveBlendParameterCount; j++) { string recursiveBlendParameter2 = blendTree2.GetRecursiveBlendParameter(j); int num2 = this.m_Controller.IndexOfParameter(recursiveBlendParameter2); if (num2 == -1) { this.m_Controller.AddParameter(recursiveBlendParameter2, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(blendTree2.GetRecursiveBlendParameterMin(j), blendTree2.GetRecursiveBlendParameterMax(j))); } else { this.m_ParameterMinMax[num2] = new Vector2(Mathf.Min(blendTree2.GetRecursiveBlendParameterMin(j), this.m_ParameterMinMax[num2][0]), Mathf.Max(blendTree2.GetRecursiveBlendParameterMax(j), this.m_ParameterMinMax[num2][1])); } } } this.m_SrcState = this.m_StateMachine.AddState(this.m_RefSrcState.name); this.m_SrcState.pushUndo = false; this.m_SrcState.hideFlags = HideFlags.HideAndDontSave; this.m_DstState = this.m_StateMachine.AddState(this.m_RefDstState.name); this.m_DstState.pushUndo = false; this.m_DstState.hideFlags = HideFlags.HideAndDontSave; this.CopyStateForPreview(this.m_RefSrcState, ref this.m_SrcState); this.CopyStateForPreview(this.m_RefDstState, ref this.m_DstState); this.m_Transition = this.m_SrcState.AddTransition(this.m_DstState, true); this.m_Transition.pushUndo = false; this.m_Transition.hideFlags = HideFlags.DontSave; this.CopyTransitionForPreview(this.m_RefTransition, ref this.m_Transition); this.DisableIKOnFeetIfNeeded(); AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); AnimatorController expr_400 = this.m_Controller; expr_400.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_400.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); } }
private void Start() { Debug.Log("Importing Animations ⊂( ・∀・) 彡 =͟͟͞͞ ⌧"); EditorCurveBinding spriteBinding = new EditorCurveBinding { type = typeof(SpriteRenderer), path = "", propertyName = "m_Sprite" }; DataItem[] jsonItems = dataLoader.dataClass.items; if (!AssetDatabase.IsValidFolder("Assets/Resources/Animation Controllers")) { AssetDatabase.CreateFolder("Assets/Resources", "Animation Controllers"); } foreach (DataItem item in jsonItems) { if (!AssetDatabase.IsValidFolder("Assets/Resources/Animation Controllers/" + item.name)) { AssetDatabase.CreateFolder("Assets/Resources/Animation Controllers", item.name); } AnimatorController controller = AnimatorController.CreateAnimatorControllerAtPath("Assets/Resources/Animation Controllers/" + item.name + "/" + item.name + ".controller"); AnimatorStateMachine root = controller.layers[0].stateMachine; TransitionClass[] transitions = item.animData.transitions; AnimClass[] animations = item.animData.animations; TriggerClass[] triggers = item.animData.triggers; foreach (AnimClass anim in animations) { Sprite[] sprites = Resources.LoadAll <Sprite>("Animation Assets/" + item.name + "/" + anim.name); ObjectReferenceKeyframe[] spriteKeyFrames = sprites.Select((sprite, index) => ( new ObjectReferenceKeyframe { time = index / anim.fps, value = sprite } )).ToArray(); AnimationClip clip = new AnimationClip() { name = anim.name }; if (anim.isLoop) { AnimationClip tempClip = new AnimationClip(); AnimationClipSettings newSettings = AnimationUtility.GetAnimationClipSettings(tempClip); newSettings.loopTime = true; AnimationUtility.SetAnimationClipSettings(clip, newSettings); } AnimationUtility.SetObjectReferenceCurve(clip, spriteBinding, spriteKeyFrames); if (anim.children != null) { AnimationEvent[] events = anim.children.Select((e, index) => ( new AnimationEvent() { stringParameter = e.name, time = e.time, functionName = "spawn" } )).ToArray(); AnimationUtility.SetAnimationEvents(clip, events); } //allows animations to build properly AssetDatabase.CreateAsset(clip, "Assets/Resources/Animation Controllers/" + item.name + "/" + clip.name + ".anim"); controller.AddMotion(clip); } foreach (TriggerClass trig in triggers) { controller.AddParameter(trig.name, AnimatorControllerParameterType.Trigger); } foreach (TransitionClass t in transitions) { AnimatorCondition[] conditionsArray = t.conditions.Select((con, index) => ( new AnimatorCondition() { mode = AnimatorConditionMode.If, parameter = con, threshold = 0 } )).ToArray(); AnimatorState origin = System.Array.Find(root.states, element => t.source.Equals(element.state.name)).state; AnimatorState target = System.Array.Find(root.states, element => t.target.Equals(element.state.name)).state; AnimatorStateTransition transition = new AnimatorStateTransition() { hasExitTime = t.hasExitTime, destinationState = target, conditions = conditionsArray }; origin.AddTransition(transition); } } Debug.Log("Animations Imported! ♪┏(・o・)┛♪┗ ( ・o・) ┓"); }