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 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 AnimationBuilder (ScmlProcessingInfo info, IDictionary<int, IDictionary<int, Sprite>> folders, IDictionary<string, Transform> transforms, IDictionary<string, SpatialInfo> defaultBones, IDictionary<string, SpriteInfo> defaultSprites, string prefabPath, AnimatorController controller) { if (S2USettings.Settings.followScmlSprite) { scmlFollower.Build (); } ProcessingInfo = info; Folders = folders; Transforms = transforms; PrefabPath = prefabPath; DefaultBones = defaultBones; DefaultSprites = defaultSprites; Root = Transforms ["rootTransform"]; Controller = controller; AnimationsPath = PrefabPath.Substring (0, PrefabPath.LastIndexOf ('.')) + "_Anims"; foreach (var item in GetOrigClips ()) { var clip = item as AnimationClip; if (clip != null) OriginalClips [clip.name] = clip; } }
void Start () { myTrans = this.transform; myAnim = this.gameObject.GetComponent<Animator>(); instance = this; artScaleCache = myTrans.localScale; }
public MecanimEvent[] GetEvents(AnimatorController controller, int layer, int stateNameHash) { try { return data[controller][layer][stateNameHash].ToArray(); } catch { return new MecanimEvent[0]; } }
public static AnimatorState[] GetAnimatorStates(AnimatorController aniController) { if (!animatorControllerAnimatorStates.ContainsKey (aniController)) { processAnimatorController (aniController); } return animatorControllerAnimatorStates [aniController]; }
internal static void OnInvalidateAnimatorController(AnimatorController controller) { if ((AnimatorControllerTool.tool != null) && (AnimatorControllerTool.tool.animatorController == controller)) { AnimatorControllerTool.tool.OnInvalidateAnimatorController(); } if ((ParameterControllerEditor.tool != null) && (ParameterControllerEditor.tool.animatorController == controller)) { ParameterControllerEditor.tool.OnInvalidateAnimatorController(); } }
private void OnEnable() { this.m_Target = (PhotonAnimatorView) target; this.m_Animator = this.m_Target.GetComponent<Animator>(); #if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 this.m_Controller = AnimatorController.GetEffectiveAnimatorController(this.m_Animator); #endif CheckIfStoredParametersExist(); }
private static AnimationClip GenerateTriggerableTransition(string name, AnimatorController controller) { AnimationClip animationClip = AnimatorController.AllocateAnimatorClip(name); AssetDatabase.AddObjectToAsset(animationClip, controller); AnimatorState animatorState = controller.AddMotion(animationClip); controller.AddParameter(name, AnimatorControllerParameterType.Trigger); AnimatorStateMachine stateMachine = controller.layers[0].stateMachine; AnimatorStateTransition animatorStateTransition = stateMachine.AddAnyStateTransition(animatorState); animatorStateTransition.AddCondition(AnimatorConditionMode.If, 0f, name); return animationClip; }
void Start() { myBody = this.GetComponent<Rigidbody2D>(); myTrans = this.transform; tagGround = GameObject.Find(this.name + "/tag_ground").transform; myAnim = AnimatorController.instance; runBonus = 0; instance = this; nbSong = 0; song = new AudioClip[20]; bossOn = true; }
private static void BuildPrefab(DirectoryInfo dictory, AnimatorController animatorCountorller) { string modelPath = "Assets/Model/" + dictory.Name + "/" + dictory.Name + ".FBX"; GameObject go = AssetDatabase.LoadAssetAtPath (modelPath, typeof(GameObject)) as GameObject; go.name = dictory.Name; Animator animator = go.GetComponent<Animator> (); animator.runtimeAnimatorController = animatorCountorller; PrefabUtility.CreatePrefab (PrefabPath + "/" + go.name + ".prefab", go); }
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; }
private static void AddStateTransition(AnimatorController ctrl, string path, AnimatorControllerLayer layer) { AnimatorStateMachine sm = layer.stateMachine; //根据动画文件读取它的AnimationClip对象 Object[] objs = AssetDatabase.LoadAllAssetsAtPath(path); List<AnimationClip> clips = new List<AnimationClip>(); for (int i = 0; i < objs.Length;i++ ) { AnimationClip clip = objs[i] as AnimationClip; if (clip != null && clip.name.IndexOf("__preview__") == -1) { clips.Add(clip); } } AnimatorState idleState = null; List<AnimatorState> otherStates = new List<AnimatorState>(); foreach (AnimationClip newClip in clips) { AnimatorState state = sm.AddState(newClip.name); state.motion = newClip; if (newClip.name == CreateAnimatorController.IdleName) { idleState = state; } else { string cond = string.Format("{0}_{1}",CreateAnimatorController.IdleName, newClip.name); ctrl.AddParameter(cond, AnimatorControllerParameterType.Bool); cond = string.Format("{1}_{0}", CreateAnimatorController.IdleName, newClip.name); ctrl.AddParameter(cond, AnimatorControllerParameterType.Bool); otherStates.Add(state); } } sm.defaultState = idleState; foreach (AnimatorState state in otherStates) { string cond = string.Format("{0}_{1}",CreateAnimatorController.IdleName, state.motion.name); AnimatorStateTransition tran = idleState.AddTransition(state); tran.AddCondition(AnimatorConditionMode.If, 0, cond); cond = string.Format("{1}_{0}", CreateAnimatorController.IdleName, state.motion.name); tran = state.AddTransition(idleState); tran.AddCondition(AnimatorConditionMode.If, 0, cond); } }
public AnimationBuilder (ScmlProcessingInfo info, IDictionary<int, IDictionary<int, Sprite>> folders, IDictionary<string, Transform> transforms, IDictionary<string, SpatialInfo> defaultBones, IDictionary<string, SpriteInfo> defaultSprites, string prefabPath, AnimatorController controller) { ProcessingInfo = info; Folders = folders; Transforms = transforms; PrefabPath = prefabPath; DefaultBones = defaultBones; DefaultSprites = defaultSprites; Root = Transforms ["rootTransform"]; Controller = controller; foreach (var item in AssetDatabase.LoadAllAssetRepresentationsAtPath(prefabPath)) { var clip = item as AnimationClip; if (clip != null) OriginalClips [clip.name] = clip; } }
void Reset() { displayEvents = null; targetController = null; targetStateMachine = null; targetState = null; targetEvent = null; selectedLayer = 0; selectedState = 0; selectedEvent = 0; MecanimEventEditorPopup.Destroy(); }
private static AnimationClip GenerateTriggerableTransition(string name, AnimatorController controller) { AnimationClip animationClip = AnimatorController.AllocateAnimatorClip(name); AssetDatabase.AddObjectToAsset(animationClip, controller); State dst = AnimatorController.AddAnimationClipToController(controller, animationClip); controller.AddParameter(name, AnimatorControllerParameterType.Trigger); StateMachine stateMachine = controller.GetLayer(0).stateMachine; Transition transition = stateMachine.AddAnyStateTransition(dst); AnimatorCondition condition = transition.GetCondition(0); condition.mode = TransitionConditionMode.If; condition.parameter = name; return animationClip; }
public void SetEvents(AnimatorController controller, int layer, int stateNameHash, MecanimEvent[] events) { if (!data.ContainsKey(controller)) { data[controller] = new Dictionary<int, Dictionary<int, List<MecanimEvent>>>(); } if (!data[controller].ContainsKey(layer)) { data[controller][layer] = new Dictionary<int, List<MecanimEvent>>(); } if (!data[controller][layer].ContainsKey(stateNameHash)) { data[controller][layer][stateNameHash] = new List<MecanimEvent>(); } data[controller][layer][stateNameHash] = new List<MecanimEvent>(events); }
private List<string> CollectParameters(AnimatorController controller, AnimatorControllerParameterType type) { List<string> list = new List<string>(); if (controller != null) { foreach (AnimatorControllerParameter parameter in controller.parameters) { if (parameter.type == type) { list.Add(parameter.name); } } } return list; }
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; }
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; }
void OnGUI() { animationController = (AnimatorController)EditorGUILayout.ObjectField("Animation Controller", animationController, typeof(AnimatorController), true); dynamicAnimation = (AnimationClip)EditorGUILayout.ObjectField("Animation", dynamicAnimation, typeof(AnimationClip), true); triggerName = EditorGUILayout.TextField("Trigger Name: ", triggerName); if(animationController && dynamicAnimation) { if(GUILayout.Button("Add Action")) { this.AddAnimation(); this.Close(); } } else { EditorGUILayout.HelpBox("All fields must be filled before continuing!", MessageType.Warning); } }
private static AnimationClip GenerateTriggerableTransition(string name, AnimatorController controller) { // Create the clip var clip = AnimatorController.AllocateAnimatorClip(name); AssetDatabase.AddObjectToAsset(clip, controller); // Create a state in the animatior controller for this clip var state = controller.AddMotion(clip); // Add a transition property controller.AddParameter(name, AnimatorControllerParameterType.Trigger); // Add an any state transition var stateMachine = controller.layers[0].stateMachine; var transition = stateMachine.AddAnyStateTransition(state); transition.AddCondition(AnimatorConditionMode.If, 0, name); return clip; }
static string GenerateCode(AnimatorController animatorController) { string intent = " "; string floatPropertyTemplate = intent + "protected readonly static int {0}Hash = {1}; public float {0}{{ get{{ return animator.GetFloat({0}Hash); }} set{{ animator.SetFloat({0}Hash, value); }}}}"; string intPropertyTemplate = intent + "protected readonly static int {0}Hash = {1}; public int {0}{{ get{{ return animator.GetInteger({0}Hash); }} set{{ animator.SetInteger({0}Hash, value); }}}}"; string boolPropertyTemplate = intent + "protected readonly static int {0}Hash = {1}; public bool {0}{{ get{{ return animator.GetBool({0}Hash); }} set{{ animator.SetBool({0}Hash, value); }}}}"; string triggerTemplate = intent + "protected readonly static int {0}Hash = {1}; public void {0}(){{ animator.SetTrigger ({0}Hash); }} public void Reset{0}() {{ animator.ResetTrigger ({0}Hash); }}"; string stateTemplate = intent + "public static readonly int {0} = {1};"; var codePath = GetPath ("Assets/AnimatorAccessHelper/Editor/Resources/AnimatorParameterImporter.txt"); var codeTemplate = File.ReadAllText (codePath); Assert.IsNotNull (codeTemplate); StringBuilder fields = new StringBuilder (); foreach (var param in animatorController.parameters) { string code = string.Empty; string name = StripSpace(param.name); if( param.type == AnimatorControllerParameterType.Bool) code = string.Format(boolPropertyTemplate, name, param.nameHash); if( param.type == AnimatorControllerParameterType.Float) code = string.Format(floatPropertyTemplate, name, param.nameHash); if( param.type == AnimatorControllerParameterType.Int) code = string.Format(intPropertyTemplate, name, param.nameHash); if( param.type == AnimatorControllerParameterType.Trigger) code = string.Format(triggerTemplate, name, param.nameHash); fields.AppendLine(code); } Dictionary<string, int> hashState = new Dictionary<string, int>(); foreach (var layer in animatorController.layers) { StateCheck(layer.stateMachine, layer.stateMachine.name + ".", ref hashState); } foreach (var states in hashState) { var code = string.Format(stateTemplate, states.Key, states.Value); fields.AppendLine(code); } return string.Format(codeTemplate, StripSpace(animatorController.name), fields.ToString()); }
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_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 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 ValidateNodeNames(AnimatorTriggeredSpecialFX fx) { Animator animator = fx.GetComponent <Animator>(); if (!animator) { // should be impossible because we explicitly RequireComponent the Animator EditorUtility.DisplayDialog("Error", "No Animator found on this GameObject!?", "OK"); return; } if (animator.runtimeAnimatorController == null) { // perfectly normal user error: they haven't plugged a controller into the Animator EditorUtility.DisplayDialog("Error", "The Animator does not have an AnimatorController in it!", "OK"); return; } // make sure there aren't any duplicated event entries! int totalErrors = 0; for (int i = 0; i < fx.m_EventsOnNodeEntry.Length; ++i) { for (int j = i + 1; j < fx.m_EventsOnNodeEntry.Length; ++j) { if (fx.m_EventsOnNodeEntry[i].m_AnimatorNodeNameHash == fx.m_EventsOnNodeEntry[j].m_AnimatorNodeNameHash && fx.m_EventsOnNodeEntry[i].m_AnimatorNodeNameHash != 0) { ++totalErrors; Debug.LogError($"Entries {i} and {j} in EventsOnNodeEntry refer to the same node name ({fx.m_EventsOnNodeEntry[i].m_AnimatorNodeName})! This is probably a copy-paste error. (But if it isn't and you intend to play two effects, remove this error-check!)"); } } } for (int i = 0; i < fx.m_EventsOnNodeExit.Length; ++i) { for (int j = i + 1; j < fx.m_EventsOnNodeExit.Length; ++j) { if (fx.m_EventsOnNodeExit[i].m_AnimatorNodeNameHash == fx.m_EventsOnNodeExit[j].m_AnimatorNodeNameHash && fx.m_EventsOnNodeExit[i].m_AnimatorNodeNameHash != 0) { ++totalErrors; Debug.LogError($"Entries {i} and {j} in EventsOnNodeExit refer to the same node name ({fx.m_EventsOnNodeExit[i].m_AnimatorNodeName})! This is probably a copy-paste error. (But if it isn't and you intend to play two effects, remove this error-check!)"); } } } // create a map of nameHash -> useful debugging information (which we display in the log if there's a problem) Dictionary <int, string> usedNames = new Dictionary <int, string>(); for (int i = 0; i < fx.m_EventsOnNodeEntry.Length; ++i) { usedNames[fx.m_EventsOnNodeEntry[i].m_AnimatorNodeNameHash] = $"{fx.m_EventsOnNodeEntry[i].m_AnimatorNodeName} (EventsOnNodeEntry index {i})"; } for (int i = 0; i < fx.m_EventsOnNodeExit.Length; ++i) { usedNames[fx.m_EventsOnNodeExit[i].m_AnimatorNodeNameHash] = $"{fx.m_EventsOnNodeExit[i].m_AnimatorNodeName} (EventsOnNodeExit index {i})"; } int totalUsedNames = usedNames.Count; // now remove all the hashes that are actually used by the controller AnimatorController controller = GetAnimatorController(animator); foreach (var layer in controller.layers) { foreach (var state in layer.stateMachine.states) { usedNames.Remove(state.state.nameHash); } } // anything that hasn't gotten removed from usedNames isn't actually valid! foreach (var hash in usedNames.Keys) { Debug.LogError("Could not find Animation node named " + usedNames[hash]); } totalErrors += usedNames.Keys.Count; if (totalErrors == 0) { EditorUtility.DisplayDialog("Success", $"All {totalUsedNames} referenced node names were found in the Animator. No errors found!", "OK!"); } else { EditorUtility.DisplayDialog("Errors", $"Found {totalErrors} errors. See the log in the Console tab for more information.", "OK"); } }
public void Inject(AnimatorController controller) { this.controller = controller; }
public static AnimatorState CreateVirtualInstance(VirtualSerializedFile virtualFile, AnimatorController controller, int stateMachineIndex, int stateIndex, Vector3f position) { return(virtualFile.CreateAsset((assetInfo) => new AnimatorState(assetInfo, controller, stateMachineIndex, stateIndex, position))); }
static void GeneratePrefabs(string name, string fbxPath, AnimatorController controller) { name = name.Replace('\\', '/'); string prefabPath = GeneratePrefabPath + name + ".prefab"; fbxPath = fbxPath.Substring(fbxPath.IndexOf("Assets\\")); GameObject go; bool ShowDestroy; if (!AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject))) { ShowDestroy = true; GameObject origalGo = AssetDatabase.LoadAssetAtPath <GameObject>(fbxPath); go = Instantiate(origalGo); } else { ShowDestroy = false; GameObject origalGo = AssetDatabase.LoadAssetAtPath <GameObject>(fbxPath); go = Instantiate(origalGo); } EditorUtility.SetDirty(go); Selection.activeObject = go; if (!go.GetComponent <Animator>()) { //Debug.Log("添加一个animator"); go.AddComponent <Animator>(); } Animator animator = go.GetComponent <Animator>(); animator.runtimeAnimatorController = controller; animator.applyRootMotion = false; if (prefabPath.Contains("300")) { animator.cullingMode = AnimatorCullingMode.CullUpdateTransforms; } else { animator.cullingMode = AnimatorCullingMode.CullCompletely; } SkinnedMeshRenderer[] SkinnedMeshRenders = go.GetComponentsInChildren <SkinnedMeshRenderer>(); foreach (SkinnedMeshRenderer _render in SkinnedMeshRenders) { _render.quality = SkinQuality.Auto; _render.lightProbeUsage = LightProbeUsage.Off; _render.reflectionProbeUsage = ReflectionProbeUsage.Off; _render.shadowCastingMode = ShadowCastingMode.On; _render.receiveShadows = false; _render.skinnedMotionVectors = false; _render.motionVectorGenerationMode = MotionVectorGenerationMode.ForceNoMotion; } if (!AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject))) { //Debug.Log(prefabPath); PrefabUtility.CreatePrefab(prefabPath, go); } else { PrefabUtility.CreatePrefab(prefabPath, go); //Debug.Log(">>>>>>>>>>>>>>>>>>>>已经存在prefab,不在生成新的prefab,如果想重新生成,请将旧的手动删除"); //Debug.Log(prefabPath); } if (ShowDestroy) { DestroyImmediate(go); } else { DestroyImmediate(go); //Resources.UnloadAsset(go); } }
public static void PasteToStateMachineTransitionParametersFromPasteboard(UnityEngine.Object transition, AnimatorController controller, bool conditions, bool parameters) { Undo.RegisterCompleteObjectUndo(transition, "Paste to Transition"); PasteToStateMachineTransitionParametersFromPasteboardInternal(transition, controller, conditions, parameters); }
public static void CopyStateMachineDataToPasteboard(UnityEngine.Object stateMachineObject, AnimatorController controller, int layerIndex) { Unsupported.CopyStateMachineDataToPasteboard(new UnityEngine.Object[] { stateMachineObject }, new Vector3[] { default(Vector3) }, controller, layerIndex); }
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) { AvatarMaskBodyPart avatarMaskBodyPart = AvatarMaskBodyPart.Root; while (avatarMaskBodyPart < AvatarMaskBodyPart.LastBodyPart && flag) { if (!this.m_LayerMask.GetHumanoidBodyPartActive(avatarMaskBodyPart)) { flag = false; } avatarMaskBodyPart++; } 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 num = this.m_Controller.IndexOfParameter(recursiveBlendParameter2); if (num == -1) { this.m_Controller.AddParameter(recursiveBlendParameter2, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(blendTree2.GetRecursiveBlendParameterMin(j), blendTree2.GetRecursiveBlendParameterMax(j))); } else { this.m_ParameterMinMax[num] = new Vector2(Mathf.Min(blendTree2.GetRecursiveBlendParameterMin(j), this.m_ParameterMinMax[num][0]), Mathf.Max(blendTree2.GetRecursiveBlendParameterMax(j), this.m_ParameterMinMax[num][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_3F0 = this.m_Controller; expr_3F0.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_3F0.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); } }
private void Start() { FirstPersonAnimator = transform.Find("FirstPerson").GetComponent <AnimatorController>(); ThirdPersonAnimator = transform.Find("ThirdPerson").GetComponent <AnimatorController>(); charControl = GetComponent <CharacterController>(); }
/// <summary> /// Adds the Ultimate Character Controller parameters to the animator controller. /// </summary> /// <param name="animatorController">The animator controller to add the parameters to.</param> public static void AddParameters(AnimatorController animatorController) { if (!HasParameter(animatorController, "HorizontalMovement")) { animatorController.AddParameter("HorizontalMovement", AnimatorControllerParameterType.Float); } if (!HasParameter(animatorController, "ForwardMovement")) { animatorController.AddParameter("ForwardMovement", AnimatorControllerParameterType.Float); } if (!HasParameter(animatorController, "Pitch")) { animatorController.AddParameter("Pitch", AnimatorControllerParameterType.Float); } if (!HasParameter(animatorController, "Yaw")) { animatorController.AddParameter("Yaw", AnimatorControllerParameterType.Float); } if (!HasParameter(animatorController, "Speed")) { animatorController.AddParameter("Speed", AnimatorControllerParameterType.Float); } if (!HasParameter(animatorController, "Height")) { animatorController.AddParameter("Height", AnimatorControllerParameterType.Float); } if (!HasParameter(animatorController, "Moving")) { animatorController.AddParameter("Moving", AnimatorControllerParameterType.Bool); } if (!HasParameter(animatorController, "Aiming")) { animatorController.AddParameter("Aiming", AnimatorControllerParameterType.Bool); } if (!HasParameter(animatorController, "MovementSetID")) { animatorController.AddParameter("MovementSetID", AnimatorControllerParameterType.Int); } if (!HasParameter(animatorController, "AbilityIndex")) { animatorController.AddParameter("AbilityIndex", AnimatorControllerParameterType.Int); } if (!HasParameter(animatorController, "AbilityChange")) { animatorController.AddParameter("AbilityChange", AnimatorControllerParameterType.Trigger); } if (!HasParameter(animatorController, "AbilityIntData")) { animatorController.AddParameter("AbilityIntData", AnimatorControllerParameterType.Int); } if (!HasParameter(animatorController, "AbilityFloatData")) { animatorController.AddParameter("AbilityFloatData", AnimatorControllerParameterType.Float); } for (int i = 0; i < 2; ++i) { var parameterName = string.Format("Slot{0}ItemID", i); if (!HasParameter(animatorController, parameterName)) { animatorController.AddParameter(parameterName, AnimatorControllerParameterType.Int); } parameterName = string.Format("Slot{0}ItemStateIndex", i); if (!HasParameter(animatorController, parameterName)) { animatorController.AddParameter(parameterName, AnimatorControllerParameterType.Int); } parameterName = string.Format("Slot{0}ItemStateIndexChange", i); if (!HasParameter(animatorController, parameterName)) { animatorController.AddParameter(parameterName, AnimatorControllerParameterType.Trigger); } parameterName = string.Format("Slot{0}ItemSubstateIndex", i); if (!HasParameter(animatorController, parameterName)) { animatorController.AddParameter(parameterName, AnimatorControllerParameterType.Int); } } if (!HasParameter(animatorController, "LegIndex")) { animatorController.AddParameter("LegIndex", AnimatorControllerParameterType.Float); } }
/// <summary> /// Generates the code necessary to recreate the states/transitions that are affected by the specified parameter name and value. /// </summary> /// <param name="animatorController">The animator controller to generate the states/transitions of.</param> /// <param name="parameterName">The name of the animator parameter which should have its states/transitions generated.</param> /// <param name="parameterValue">The value of the animator parameter which should have its states/transitions generated.</param> /// <param name="parentObject">The object which called GenerateAnimator.</param> /// <param name="baseDirectory">The directory that the scripts are located.</param> /// <returns>The file path of the generated code.</returns> public static string GenerateAnimatorCode(AnimatorController animatorController, AnimatorController firstPersonAnimatorController, string parameterName, float parameterValue, object parentObject, string baseDirectory) { var generatedCode = new StringBuilder(); var generatedStateMachineCode = GenerateAnimatorCode(animatorController, "animatorController", parameterName, parameterValue, generatedCode); generatedStateMachineCode = GenerateAnimatorCode(firstPersonAnimatorController, "firstPersonAnimatorController", parameterName, parameterValue, generatedCode) || generatedStateMachineCode; // The code for the animator controller has been generated. Add it to a new file. if (generatedStateMachineCode) { // Prepare the string for being appended to a file. var parentName = parentObject.GetType().Name; var path = EditorUtility.SaveFilePanel("Save Item", baseDirectory + "/Abilities", parentName + "InspectorDrawer.cs", "cs"); if (path.Length != 0 && Application.dataPath.Length < path.Length) { var fileString = new StringBuilder(); var fileName = Path.GetFileNameWithoutExtension(path); // If the file already exists then the generated code should be appended to the end. if (File.Exists(path)) { using (var sr = new StreamReader(path)) { var contents = sr.ReadToEnd(); var startIndex = -1; if ((startIndex = contents.IndexOf(c_StartGeneratedCodeComment)) > -1) { // Remove the contents after the start generated code comment so the file can start fresh. contents = contents.Remove(startIndex); } else { // Remove the last two curly brackets if the code comment doesn't exist. var count = 0; while (count < 2) { contents = contents.TrimEnd(new char[] { ' ', '\n', '\r', '\t' }); contents.Remove(contents.Length - 1); count++; } } contents = contents.TrimEnd(new char[] { ' ', '\t' }); fileString.Append(contents); } } else { // Start a new file. fileString.AppendLine("using UnityEngine;"); fileString.AppendLine("using UnityEditor;"); fileString.AppendLine("using UnityEditor.Animations;"); fileString.AppendLine("using Opsive.UltimateCharacterController.Editor.Utility;"); fileString.AppendLine(); fileString.AppendLine("namespace Opsive.UltimateCharacterController.Editor.Inspectors.Character.Abilities"); fileString.AppendLine("{"); fileString.AppendLine("\t/// <summary>"); fileString.AppendLine("\t/// Draws a custom inspector for the " + parentName + " Ability."); fileString.AppendLine("\t/// </summary>"); fileString.AppendLine("\t[InspectorDrawer(typeof(" + parentObject.GetType().FullName + "))]"); fileString.AppendLine("\tpublic class " + fileName + " : AbilityInspectorDrawer"); fileString.AppendLine("\t{"); } // Add the generated code. fileString.AppendLine("\t\t" + c_StartGeneratedCodeComment); fileString.AppendLine("\t\t// ------- Do NOT make any changes below. Changes will be removed when the animator is generated again. -------"); fileString.AppendLine("\t\t// ------------------------------------------------------------------------------------------------------------"); fileString.AppendLine(); fileString.AppendLine("\t\t/// <summary>"); fileString.AppendLine("\t\t/// Returns true if the ability can build to the animator."); fileString.AppendLine("\t\t/// </summary>"); fileString.AppendLine("\t\tpublic override bool CanBuildAnimator { get { return true; } }"); fileString.AppendLine(); fileString.AppendLine("\t\t/// <summary>"); fileString.AppendLine("\t\t/// An editor only method which can add the abilities states/transitions to the animator."); fileString.AppendLine("\t\t/// </summary>"); fileString.AppendLine("\t\t/// <param name=\"animatorController\">The Animator Controller to add the states to.</param>"); fileString.AppendLine("\t\t/// <param name=\"firstPersonAnimatorController\">The first person Animator Controller to add the states to.</param>"); fileString.AppendLine("\t\tpublic override void BuildAnimator(AnimatorController animatorController, AnimatorController firstPersonAnimatorController)"); fileString.AppendLine("\t\t{"); fileString.Append(generatedCode.ToString()); fileString.AppendLine("\t\t}"); fileString.AppendLine("\t}"); fileString.AppendLine("}"); // Save the file. var file = new StreamWriter(path, false); file.Write(fileString.ToString()); file.Close(); AssetDatabase.Refresh(); return(path); } } return(string.Empty); }
/// <summary> /// Generates the code necessary to recreate the states/transitions that are affected by the specified parameter name and value. /// </summary> /// <param name="animatorController">The animator controller to generate the states/transitions of.</param> /// <param name="animatorVariableName">The name of the animator controller variable name. This name is used within the generated code.</param> /// <param name="parameterName">The name of the animator parameter which should have its states/transitions generated.</param> /// <param name="parameterValue">The value of the animator parameter which should have its states/transitions generated.</param> /// <param name="generatedCode">The final generated code.</param> /// <returns>Was the animator code generated?</returns> private static bool GenerateAnimatorCode(AnimatorController animatorController, string animatorVariableName, string parameterName, float parameterValue, StringBuilder generatedCode) { var generateAnimatorCode = false; var motionSet = new HashSet <UnityEngine.Motion>(); for (int i = 0; i < animatorController.layers.Length; ++i) { var layer = animatorController.layers[i]; var stateMachine = layer.stateMachine; var transitions = new List <AnimatorTransition>(); FindTransitions(stateMachine.anyStateTransitions, parameterName, parameterValue, transitions, true); FindTransitions(stateMachine.entryTransitions, parameterName, parameterValue, transitions, false); // The list of transitions have been found which match the given parameters. The transition has a reference to the state // but not the state machine so another search needs to be done which finds the parent state machine. If the state machine // has the state then that state machine (and any child state machines) should be generated. var stateMachines = new List <ChildAnimatorStateMachine>(); for (int j = 0; j < transitions.Count; ++j) { for (int k = 0; k < stateMachine.stateMachines.Length; ++k) { if (HasState(stateMachine.stateMachines[k].stateMachine, transitions[j].Transition.destinationState)) { stateMachines.Add(stateMachine.stateMachines[k]); } } } // Create all of the states under the highest level child state machine. if (stateMachines.Count > 0) { generateAnimatorCode = true; if (generatedCode.Length > 0) { generatedCode.AppendLine(); } // The state machine should start fresh. var baseStateMachine = stateMachines[0]; var baseStateMachineName = "baseStateMachine" + i; generatedCode.AppendLine("\t\t\tvar " + baseStateMachineName + " = " + animatorVariableName + ".layers[" + i + "].stateMachine;"); generatedCode.AppendLine(); generatedCode.AppendLine("\t\t\t// The state machine should start fresh."); generatedCode.AppendLine("\t\t\tfor (int i = 0; i < " + animatorVariableName + ".layers.Length; ++i) {"); generatedCode.AppendLine("\t\t\t\tfor (int j = 0; j < " + baseStateMachineName + ".stateMachines.Length; ++j) {"); generatedCode.AppendLine("\t\t\t\t\tif (" + baseStateMachineName + ".stateMachines[j].stateMachine.name == \"" + baseStateMachine.stateMachine.name + "\") {"); generatedCode.AppendLine("\t\t\t\t\t\t" + baseStateMachineName + ".RemoveStateMachine(" + baseStateMachineName + ".stateMachines[j].stateMachine);"); generatedCode.AppendLine("\t\t\t\t\t\tbreak;"); generatedCode.AppendLine("\t\t\t\t\t}"); generatedCode.AppendLine("\t\t\t\t}"); generatedCode.AppendLine("\t\t\t}"); generatedCode.AppendLine(); // Generate the AnimationClips first so they can be later referenced by the states. generatedCode.AppendLine("\t\t\t// AnimationClip references."); GenerateMotions(baseStateMachine, motionSet, generatedCode); generatedCode.AppendLine(); // Generate the states and transition within each substate machine. GenerateStateMachine(baseStateMachineName, baseStateMachine, generatedCode); // Add the any state and entry transitions. generatedCode.AppendLine("\t\t\t// State Machine Transitions."); for (int j = 0; j < transitions.Count; ++j) { GenerateTransition(baseStateMachineName, transitions[j].Transition, false, transitions[j].AnyStateTransition, generatedCode); if (j != transitions.Count - 1) { generatedCode.AppendLine(); } } } } return(generateAnimatorCode); }
internal static extern void CopyStateMachineDataToPasteboard(UnityEngine.Object[] stateMachineObjects, AnimatorStateMachine context, Vector3[] monoPositions, AnimatorController controller, int layerIndex);
/// <summary> /// Merges a controller "as new" with the specified playable layer on an avatar's descriptor, /// assigns it on the avatar, and stores the new controller at the given path. /// </summary> /// <param name="descriptor">The avatar descriptor that merging is being done on.</param> /// <param name="controllerToAdd">The controller to merge to the playable layer.</param> /// <param name="playable">The playable layer to merge to.</param> /// <param name="directory">The unique directory to store the new merged controller, ex. "Assets/MyCoolScript/GeneratedAssets/725638/".</param> /// <param name="overwrite">Optionally, choose to not overwrite an asset of the same name in directory. See class for more info.</param> public static void MergeToLayer(VRCAvatarDescriptor descriptor, AnimatorController controllerToAdd, PlayableLayer playable, string directory, bool overwrite = true) { int layer = (int)playable; if (descriptor == null) { Debug.LogError("The avatar descriptor is null! Merging was not performed."); return; } else if (controllerToAdd == null) { Debug.LogError("The controller to add is null! Merging was not performed."); return; } else if ((layer < 0) || (layer > 4)) { Debug.LogError("Layer is out of bounds! Merging was not performed."); return; } else if (layer < 4) // fx layer has no default layer { if ((AssetDatabase.LoadAssetAtPath(_defaultLayerPath[layer], typeof(AnimatorController)) as AnimatorController) == null) { Debug.LogError("Couldn't find VRChat's default animator controller at path '" + _defaultLayerPath[layer] + "'! Merging was not performed."); return; } } else if (string.IsNullOrEmpty(directory)) { Debug.Log("Directory was not specified, storing new controller in " + DEFAULT_DIRECTORY); directory = DEFAULT_DIRECTORY; } if ((descriptor.baseAnimationLayers[layer].isDefault) || descriptor.baseAnimationLayers[layer].animatorController == null) { descriptor.customizeAnimationLayers = true; descriptor.baseAnimationLayers[layer].isDefault = false; AnimatorController controllerFromNew = new AnimatorController(); string pathFromNew = directory + playable.ToString() + ".controller"; if (layer == 4) // fx layer has no default layer { // you cannot add a layer to a controller without creating its asset first AssetDatabase.CreateAsset(controllerFromNew, pathFromNew); controllerFromNew.AddLayer("Base Layer"); } else { AssetDatabase.CopyAsset(_defaultLayerPath[layer], pathFromNew); controllerFromNew = AssetDatabase.LoadAssetAtPath(pathFromNew, typeof(AnimatorController)) as AnimatorController; } descriptor.baseAnimationLayers[layer].animatorController = controllerFromNew; } string path = (directory + descriptor.baseAnimationLayers[layer].animatorController.name + ".controller"); path = (overwrite) ? path : AssetDatabase.GenerateUniqueAssetPath(path); if (AssetDatabase.GetAssetPath(descriptor.baseAnimationLayers[layer].animatorController) != path) // if we have not made a copy yet { // CopyAsset with two identical strings yields exception AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(descriptor.baseAnimationLayers[layer].animatorController), path); } AnimatorController controllerOriginal = AssetDatabase.LoadAssetAtPath(path, typeof(AnimatorController)) as AnimatorController; AnimatorController mergedController = AnimatorCloner.MergeControllers(controllerOriginal, controllerToAdd, null, false); descriptor.baseAnimationLayers[layer].animatorController = mergedController; AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); }
public static void CopyStateMachineDataToPasteboard(UnityEngine.Object stateMachineObject, AnimatorController controller, int layerIndex) { CopyStateMachineDataToPasteboard(new UnityEngine.Object[] { stateMachineObject }, null, new Vector3[] { new Vector3() }, controller, layerIndex); }
public static void SetPushUndo(this AnimatorController controller, bool val) { InitType(); property_pushUndo.SetValue(controller, val, null); }
private void ResampleTransition(AnimatorStateTransition transition, AvatarMask layerMask, TransitionPreview.TransitionInfo info, Animator previewObject) { this.m_IsResampling = true; this.m_MustResample = false; bool flag = this.m_RefTransition != transition; this.m_RefTransition = transition; this.m_RefTransitionInfo = info; this.m_LayerMask = layerMask; if (this.m_AvatarPreview != null) { this.m_AvatarPreview.OnDestroy(); this.m_AvatarPreview = null; } this.ClearController(); Motion motion = this.m_RefSrcState.motion; this.Init(previewObject, (!(motion != null)) ? this.m_RefDstState.motion : motion); if (this.m_Controller == null) { return; } this.m_AvatarPreview.Animator.allowConstantClipSamplingOptimization = false; this.m_StateMachine.defaultState = this.m_DstState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-05f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); float length = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex).length; this.m_StateMachine.defaultState = this.m_SrcState; this.m_Transition.mute = false; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-05f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); float length2 = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex).length; if (this.m_LayerIndex > 0) { this.m_AvatarPreview.Animator.stabilizeFeet = false; } float num = length2 * this.m_RefTransition.exitTime + this.m_Transition.duration * ((!this.m_RefTransition.hasFixedDuration) ? length2 : 1f) + length; if (num > 2000f) { Debug.LogWarning("Transition duration is longer than 2000 second, Disabling previewer."); this.m_ValidTransition = false; return; } float num2 = (this.m_RefTransition.exitTime <= 0f) ? length2 : (length2 * this.m_RefTransition.exitTime); float num3 = (num2 <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(num2 / 300f, 0.0333333351f), num2 / 5f); float num4 = (length <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length / 300f, 0.0333333351f), length / 5f); num3 = Mathf.Max(num3, num / 600f); num4 = Mathf.Max(num4, num / 600f); float num5 = num3; float num6 = 0f; bool flag2 = false; bool flag3 = false; bool flag4 = false; this.m_AvatarPreview.Animator.StartRecording(-1); this.m_LeftStateWeightA = 0f; this.m_LeftStateTimeA = 0f; this.m_AvatarPreview.Animator.Update(0f); while (!flag4) { this.m_AvatarPreview.Animator.Update(num5); AnimatorStateInfo currentAnimatorStateInfo = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex); num6 += num5; if (!flag2) { this.m_LeftStateWeightA = (this.m_LeftStateWeightB = currentAnimatorStateInfo.normalizedTime); this.m_LeftStateTimeA = (this.m_LeftStateTimeB = num6); flag2 = true; } if (flag3 && num6 >= num) { flag4 = true; } if (!flag3 && currentAnimatorStateInfo.IsName(this.m_DstState.name)) { this.m_RightStateWeightA = currentAnimatorStateInfo.normalizedTime; this.m_RightStateTimeA = num6; flag3 = true; } if (!flag3) { this.m_LeftStateWeightB = currentAnimatorStateInfo.normalizedTime; this.m_LeftStateTimeB = num6; } if (flag3) { this.m_RightStateWeightB = currentAnimatorStateInfo.normalizedTime; this.m_RightStateTimeB = num6; } if (this.m_AvatarPreview.Animator.IsInTransition(this.m_LayerIndex)) { num5 = num4; } } float stopTime = num6; this.m_AvatarPreview.Animator.StopRecording(); if (Mathf.Approximately(this.m_LeftStateWeightB, this.m_LeftStateWeightA) || Mathf.Approximately(this.m_RightStateWeightB, this.m_RightStateWeightA)) { Debug.LogWarning("Difference in effective length between states is too big. Transition preview will be disabled."); this.m_ValidTransition = false; return; } float num7 = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); float num8 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); if (this.m_MustSampleMotions) { this.m_MustSampleMotions = false; this.m_SrcPivotList.Clear(); this.m_DstPivotList.Clear(); num5 = num4; this.m_StateMachine.defaultState = this.m_DstState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(0f); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); for (num6 = 0f; num6 <= num8; num6 += num5 * 2f) { Timeline.PivotSample pivotSample = new Timeline.PivotSample(); pivotSample.m_Time = num6; pivotSample.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; this.m_DstPivotList.Add(pivotSample); this.m_AvatarPreview.Animator.Update(num5 * 2f); } num5 = num3; this.m_StateMachine.defaultState = this.m_SrcState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); for (num6 = 0f; num6 <= num7; num6 += num5 * 2f) { Timeline.PivotSample pivotSample2 = new Timeline.PivotSample(); pivotSample2.m_Time = num6; pivotSample2.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; this.m_SrcPivotList.Add(pivotSample2); this.m_AvatarPreview.Animator.Update(num5 * 2f); } this.m_Transition.mute = false; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); } this.m_Timeline.StopTime = (this.m_AvatarPreview.timeControl.stopTime = stopTime); this.m_AvatarPreview.timeControl.currentTime = this.m_Timeline.Time; if (flag) { Timeline arg_78B_0 = this.m_Timeline; float num9 = this.m_AvatarPreview.timeControl.currentTime = (this.m_AvatarPreview.timeControl.startTime = 0f); this.m_Timeline.StartTime = num9; arg_78B_0.Time = num9; this.m_Timeline.ResetRange(); } this.m_AvatarPreview.Animator.StartPlayback(); this.m_IsResampling = false; }
void ParameterSetterSetup(SerializedProperty property) { setupCalled = true; animatorProperty = property.FindPropertyRelative("animator"); parameterNameProperty = property.FindPropertyRelative("parameterName"); parameterTypeProperty = property.FindPropertyRelative("parameterType"); boolValueProperty = property.FindPropertyRelative("boolValue"); floatValueProperty = property.FindPropertyRelative("floatValue"); intValueProperty = property.FindPropertyRelative("intValue"); if (animatorProperty.objectReferenceValue == null) { parameterNames = null; return; } Animator animator = animatorProperty.objectReferenceValue as Animator; if (animator.runtimeAnimatorController == null) { parameterNames = null; return; } AnimatorController animatorController = animator.runtimeAnimatorController as AnimatorController; AnimatorControllerParameter[] parameters = animatorController.parameters; parameterNames = new string[parameters.Length]; parameterTypes = new CharacterStateSetter.ParameterSetter.ParameterType[parameters.Length]; for (int i = 0; i < parameterNames.Length; i++) { parameterNames[i] = parameters[i].name; switch (parameters[i].type) { case AnimatorControllerParameterType.Float: parameterTypes[i] = CharacterStateSetter.ParameterSetter.ParameterType.Float; break; case AnimatorControllerParameterType.Int: parameterTypes[i] = CharacterStateSetter.ParameterSetter.ParameterType.Int; break; case AnimatorControllerParameterType.Bool: parameterTypes[i] = CharacterStateSetter.ParameterSetter.ParameterType.Bool; break; case AnimatorControllerParameterType.Trigger: parameterTypes[i] = CharacterStateSetter.ParameterSetter.ParameterType.Trigger; break; default: throw new ArgumentOutOfRangeException(); } } for (int i = 0; i < parameterNames.Length; i++) { if (parameterNames[i] == parameterNameProperty.stringValue) { parameterNameIndex = i; parameterTypeProperty.enumValueIndex = (int)parameterTypes[i]; } } }
static string Nicify(SerializedProperty sp, Object o, Object main, SearchTarget target) { // return sp.propertyPath; string nice = string.Empty; switch (o) { case AnimatorController _: { return(Nice(sp.propertyPath)); } case BlendTree blendTree: { return($"{blendTree.name}({o.GetType().Name})"); } case AnimatorState animatorState: { if (main is AnimatorController animatorController) { var bread = GetBread(animatorController, animatorState); return($"{bread}{animatorState.name}"); } break; } case StateMachineBehaviour smb: { var ctx = AnimatorController.FindStateMachineBehaviourContext(smb); if (ctx.Length == 0) { break; } var first = ctx[0]; var bread = string.Empty; switch (first.animatorObject) { case AnimatorStateMachine _: // nothing break; case AnimatorState ast: { bread = GetBread(first.animatorController, ast); break; } } return($"{bread}{first.animatorObject.name}"); } case Material _: nice = sp.displayName; break; default: { nice = Nice(sp.propertyPath); break; } } nice = string.Format("{0}.{1}", o.GetType().Name, nice); return(nice); }
public static void PasteToStateMachineFromPasteboard(AnimatorStateMachine sm, AnimatorController controller, int layerIndex, Vector3 position) { Undo.RegisterCompleteObjectUndo(sm, "Paste to StateMachine"); PasteToStateMachineFromPasteboardInternal(sm, controller, layerIndex, position); }
internal static extern void PasteToStateMachineTransitionParametersFromPasteboardInternal(UnityEngine.Object transition, AnimatorController controller, bool conditions, bool parameters);
private void ChangeHitState() { bIsHurt = !bIsHurt; AnimatorController.SetBool(hitHash, bIsHurt); }
public void Shoot(bool activateCallbacks = false) { ShootSystem.Shoot(activateCallbacks); AnimatorController.Shoot(); }
internal static extern void PasteToStateMachineFromPasteboardInternal(AnimatorStateMachine sm, AnimatorController controller, int layerIndex, Vector3 position);
private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary <int, IDictionary <int, Sprite> > folders) { var controllerPath = string.Format("{0}/{1}.controller", directory, entity.name); var animator = instance.GetComponent <Animator> (); //Fetches the prefab's Animator if (animator == null) { animator = instance.AddComponent <Animator> (); //Or creates one if it doesn't exist } AnimatorController controller = null; if (animator.runtimeAnimatorController != null) //The controller we use is hopefully the controller attached to the animator { controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController (AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController; } if (controller == null) //Otherwise we have to check the AssetDatabase for our controller { controller = (AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimatorController)); if (controller == null) { controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath); //Or create a new one if it doesn't exist. ProcessingInfo.NewControllers.Add(controller); } animator.runtimeAnimatorController = controller; } var transforms = new Dictionary <string, Transform> (); //All of the bones and sprites, identified by TimeLine.name, because those are truly unique transforms ["rootTransform"] = instance.transform; //The root GameObject needs to be part of this hierarchy as well var defaultBones = new Dictionary <string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation var defaultSprites = new Dictionary <string, SpriteInfo> (); //They are used as control values in determining whether something has changed var animBuilder = new AnimationBuilder(ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller); var firstAnim = true; //The prefab's graphic will be determined by the first frame of the first animation foreach (var animation in entity.animations) { var timeLines = new Dictionary <int, TimeLine> (); foreach (var timeLine in animation.timelines) //TimeLines hold all the critical data such as positioning and graphics used { timeLines [timeLine.id] = timeLine; } foreach (var key in animation.mainlineKeys) { var parents = new Dictionary <int, string> (); //Parents are referenced by different IDs V_V parents [-1] = "rootTransform"; //This is where "-1 == no parent" comes in handy var boneRefs = new Queue <Ref> (key.boneRefs ?? new Ref[0]); while (boneRefs.Count > 0) { var bone = boneRefs.Dequeue(); var timeLine = timeLines [bone.timeline]; parents [bone.id] = timeLine.name; if (!transforms.ContainsKey(timeLine.name)) //We only need to go through this once, so ignore it if it's already in the dict { if (parents.ContainsKey(bone.parent)) //If the parent cannot be found, it will probably be found later, so save it { var parentID = parents [bone.parent]; var parent = transforms [parentID]; var child = parent.Find(timeLine.name); //Try to find the child transform if it exists if (child == null) //Or create a new one { child = new GameObject(timeLine.name).transform; child.SetParent(parent); } transforms [timeLine.name] = child; var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find(timeLine.keys, x => x.id == bone.key).info; if (!spatialInfo.processed) { SpatialInfo parentInfo; defaultBones.TryGetValue(parentID, out parentInfo); spatialInfo.Process(parentInfo); } child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f); child.localRotation = spatialInfo.rotation; child.localScale = new Vector3(spatialInfo.scale_x, spatialInfo.scale_y, 1f); } else { boneRefs.Enqueue(bone); } } } foreach (var oref in key.objectRefs) { var timeLine = timeLines [oref.timeline]; if (!transforms.ContainsKey(timeLine.name)) //Same as above { var parentID = parents [oref.parent]; var parent = transforms [parentID]; var child = parent.Find(timeLine.name); if (child == null) { child = new GameObject(timeLine.name).transform; child.SetParent(parent); } transforms [timeLine.name] = child; var swapper = child.GetComponent <SpriteSwapper> (); //Destroy the Sprite Swapper, we'll make a new one later if (swapper != null) { DestroyImmediate(swapper); } var renderer = child.GetComponent <SpriteRenderer> (); //Get or create a Sprite Renderer if (renderer == null) { renderer = child.gameObject.AddComponent <SpriteRenderer> (); } var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find(timeLine.keys, x => x.id == 0).info; renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file]; if (!spriteInfo.processed) { SpatialInfo parentInfo; defaultBones.TryGetValue(parentID, out parentInfo); spriteInfo.Process(parentInfo); } child.localPosition = new Vector3(spriteInfo.x, spriteInfo.y, oref.z_index); //Z-index helps determine draw order child.localEulerAngles = new Vector3(0f, 0f, spriteInfo.angle); //The reason I don't use layers or layer orders is because child.localScale = new Vector3(spriteInfo.scale_x, spriteInfo.scale_y, 1f); //There tend to be a LOT of body parts, it's better to treat var color = renderer.color; //The entity as a single sprite for layer sorting purposes. color.a = spriteInfo.a; renderer.color = color; if (!firstAnim) { child.gameObject.SetActive(false); //Disable the GameObject if this isn't the first frame of the first animation } } } if (firstAnim) { firstAnim = false; } } try { animBuilder.Build(animation, timeLines); //Builds the currently processed AnimationClip, see AnimationBuilder for more info } catch (Exception e) { Debug.LogErrorFormat("Unable to build animation '{0}' for '{1}', reason: {2}", animation.name, entity.name, e); } } if (instance.GetComponent <EntityRenderer> () == null) { instance.AddComponent <EntityRenderer> (); //Adds an EntityRenderer if one is not already present } PrefabUtility.ReplacePrefab(instance, prefab, ReplacePrefabOptions.ConnectToPrefab); DestroyImmediate(instance); //Apply the instance's changes to the prefab, then destroy the instance. }
static void InitDefaults() { foreach (var kv in animLayerToDefaultFile) { if (kv.Value == null) { LyumaAv3Runtime.animLayerToDefaultController[kv.Key] = null; } else { AnimatorController ac = AssetDatabase.LoadAssetAtPath <AnimatorController>("Assets/VRCSDK/Examples3/Animation/Controllers/" + kv.Value + ".controller"); if (ac == null) { Debug.LogWarning("Failed to resolve animator controller " + kv.Value + " for " + kv.Key); ac = null; } LyumaAv3Runtime.animLayerToDefaultController[kv.Key] = ac; } } foreach (var kv in animLayerToDefaultAvaMaskFile) { if (kv.Value == null) { LyumaAv3Runtime.animLayerToDefaultAvaMask[kv.Key] = null; } else { AvatarMask mask = null; foreach (var guid in AssetDatabase.FindAssets(kv.Value)) { string path = AssetDatabase.GUIDToAssetPath(guid); mask = AssetDatabase.LoadAssetAtPath <AvatarMask>(path); } if (mask == null) { Debug.LogWarning("Failed to resolve avatar mask " + kv.Value + " for " + kv.Key); mask = new AvatarMask(); } LyumaAv3Runtime.animLayerToDefaultAvaMask[kv.Key] = mask; } } foreach (string guid in AssetDatabase.FindAssets("EmptyController")) { LyumaAv3Emulator.EmptyController = AssetDatabase.LoadAssetAtPath <RuntimeAnimatorController>(AssetDatabase.GUIDToAssetPath(guid)); } LyumaAv3Runtime.updateSelectionDelegate = (go) => { if (go == null && LyumaAv3Emulator.emulatorInstance != null) { Debug.Log("Resetting selected object: " + LyumaAv3Emulator.emulatorInstance); go = LyumaAv3Emulator.emulatorInstance.gameObject; } Debug.Log("Setting selected object: " + go); Selection.SetActiveObjectWithContext(go, go); // Highlighter.Highlight("Inspector", "Animator To Debug"); }; LyumaAv3Runtime.addRuntimeDelegate = (runtime) => { MoveComponentToTop(runtime); }; LyumaAv3Menu.addRuntimeDelegate = (menu) => { MoveComponentToTop(menu); }; }
private static void CreateAnimationControllerWithClips(MenuCommand menuCommand) { var modelController = menuCommand.context as ModelController; var animationClipFolderPath = EditorUtility.OpenFolderPanel("Select animation clip parent folder", Application.dataPath, string.Empty); if (!string.IsNullOrEmpty(animationClipFolderPath)) { // Get animation clips from folder var animationClips = GetLayeredAnimationClips(animationClipFolderPath); // Return when no clips found if (animationClips.Count == 0) { Debug.LogWarning("No animation clips found"); return; } // Make path to create new animator controller var animatorControllerPath = "Assets" + animationClipFolderPath.Replace(Application.dataPath, string.Empty); animatorControllerPath = Path.Combine(animatorControllerPath, $"{modelController.gameObject.name}.controller"); if (AssetDatabase.LoadAssetAtPath <RuntimeAnimatorController>(animatorControllerPath) != null) { // Confirm overwrite when exists if (!EditorUtility.DisplayDialog("AnimatorController exists", $"AnimatorController already exists at {animatorControllerPath}. Are you sure to overwrite?", "OK", "Cancel")) { return; } } // Create new animator controller var animatorController = AnimatorController.CreateAnimatorControllerAtPath(animatorControllerPath); foreach (var kv in animationClips) { // Select layer var layerName = kv.Key; var putOnBaseLayer = layerName == "Base layer" || EditorUtility.DisplayDialog("Select Layer", $"{kv.Value.Count} clips found in {layerName}. Put these clips on ...", "Base Layer", $"{layerName}"); if (!putOnBaseLayer) { animatorController.AddLayer(layerName); } var layer = putOnBaseLayer ? animatorController.layers[0] : animatorController.layers.Last(); // Create default state if (!layer.stateMachine.states.Select(st => st.state.name).Contains("Default")) { var defaultState = layer.stateMachine.AddState("Default"); if (putOnBaseLayer && kv.Value.Count > 0) { defaultState.motion = kv.Value[0]; } } // Put animation clips on layer foreach (var clip in kv.Value) { var state = layer.stateMachine.AddState(clip.name); state.motion = clip; } } // Set controller to animator var animator = modelController.gameObject.GetComponent <Animator>(); if (animator != null) { animator.runtimeAnimatorController = animatorController; } } }
public ControllerJson(AnimatorController animationController, string assetName, Urho3DEngine engine, PrefabContext prefabContext) { this.name = engine.DecorateName(animationController.name); layers = animationController.layers.Select((_, index) => new LayerJson(_, assetName, index, engine, prefabContext)).ToArray(); }
internal static void PasteToStateMachineFromPasteboardInternal(AnimatorStateMachine sm, AnimatorController controller, int layerIndex, Vector3 position) { INTERNAL_CALL_PasteToStateMachineFromPasteboardInternal(sm, controller, layerIndex, ref position); }
public bool Eval(AnimatorController controller) { return(expected == controller.GetBool(variableName)); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { //base.OnGUI(position, property, label); //current = EditorGUILayout.Popup(current, new[] {"11", "22"}); _ac = EditorGUILayout.ObjectField(new GUIContent("Controller"), _ac, typeof(AnimatorController), false) as AnimatorController; }
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 }
protected override void DrawAnimatorControllerProperty(Rect position, SerializedProperty property, AnimatorController animatorController) { var propertyStringValue = property.hasMultipleDifferentValues ? "-" : property.stringValue; var content = String.IsNullOrEmpty(propertyStringValue) ? new GUIContent("<None>") : new GUIContent(propertyStringValue); if (GUI.Button(position, content, EditorStyles.popup)) { StateSelector(property, animatorController); } }