Exemplo n.º 1
0
        private static bool CreateAnimation(GameObject gameObject, UnityEngine.Object[] frames)
        {
            Array.Sort <UnityEngine.Object>(frames, (UnityEngine.Object a, UnityEngine.Object b) => EditorUtility.NaturalCompare(a.name, b.name));
            string message       = string.Format("Create a new animation for the game object '{0}':", gameObject.name);
            string directoryName = Path.GetDirectoryName(AssetDatabase.GetAssetPath(frames[0]));
            string text          = EditorUtility.SaveFilePanelInProject("Create New Animation", "New Animation", "anim", message, directoryName);

            if (string.IsNullOrEmpty(text))
            {
                return(false);
            }
            AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(true);

            AssetDatabase.CreateAsset(animationClip, text);
            AnimationSelection.AddClipToAnimatorComponent(gameObject, animationClip);
            animationClip.frameRate = 12f;
            ObjectReferenceKeyframe[] array = new ObjectReferenceKeyframe[frames.Length];
            for (int i = 0; i < array.Length; i++)
            {
                array[i]       = default(ObjectReferenceKeyframe);
                array[i].value = SpriteUtility.RemapObjectToSprite(frames[i]);
                array[i].time  = (float)i / animationClip.frameRate;
            }
            EditorCurveBinding binding = EditorCurveBinding.PPtrCurve(string.Empty, typeof(SpriteRenderer), "m_Sprite");

            AnimationUtility.SetObjectReferenceCurve(animationClip, binding, array);
            return(true);
        }
Exemplo n.º 2
0
		private static bool CreateAnimation(GameObject gameObject, UnityEngine.Object[] frames)
		{
			Array.Sort<UnityEngine.Object>(frames, (UnityEngine.Object a, UnityEngine.Object b) => EditorUtility.NaturalCompare(a.name, b.name));
			string message = string.Format("Create a new animation for the game object '{0}':", gameObject.name);
			string directoryName = Path.GetDirectoryName(AssetDatabase.GetAssetPath(frames[0]));
			string text = EditorUtility.SaveFilePanelInProject("Create New Animation", "New Animation", "anim", message, directoryName);
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
			AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(true);
			AssetDatabase.CreateAsset(animationClip, text);
			AnimationSelection.AddClipToAnimatorComponent(gameObject, animationClip);
			animationClip.frameRate = 12f;
			ObjectReferenceKeyframe[] array = new ObjectReferenceKeyframe[frames.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = default(ObjectReferenceKeyframe);
				array[i].value = SpriteUtility.RemapObjectToSprite(frames[i]);
				array[i].time = (float)i / animationClip.frameRate;
			}
			EditorCurveBinding binding = EditorCurveBinding.PPtrCurve(string.Empty, typeof(SpriteRenderer), "m_Sprite");
			AnimationUtility.SetObjectReferenceCurve(animationClip, binding, array);
			return true;
		}
Exemplo n.º 3
0
        private static void CreateAnimation(List <Sprite> sprites, string path)
        {
            var frameCount  = sprites.Count;
            var frameLength = 1f / 30f;

            var name = Path.GetFileNameWithoutExtension(path);
            var clip = new AnimationClip();

            clip.frameRate = 30f;
            clip.name      = name;
            //AnimationUtility.GetAnimationClipSettings(clip);

            EditorCurveBinding curveBinding = new EditorCurveBinding();

            curveBinding.type         = typeof(SpriteRenderer);
            curveBinding.propertyName = "m_Sprite";

            ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[frameCount];

            for (int i = 0; i < frameCount; i++)
            {
                ObjectReferenceKeyframe kf = new ObjectReferenceKeyframe();
                kf.time      = i * frameLength;
                kf.value     = sprites[i];
                keyFrames[i] = kf;
            }

            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);

            var startIndex = path.IndexOf("Assets/");

            AssetDatabase.CreateAsset(clip, path.Substring(startIndex));
            AssetDatabase.Refresh();
            AssetDatabase.SaveAssets();
        }
Exemplo n.º 4
0
		public static void SetObjectReferenceCurve(AnimationClip clip, EditorCurveBinding binding, ObjectReferenceKeyframe[] keyframes)
		{
			AnimationUtility.Internal_SetObjectReferenceCurve(clip, binding, keyframes);
			if (AnimationUtility.onCurveWasModified != null)
			{
				AnimationUtility.onCurveWasModified(clip, binding, (keyframes == null) ? AnimationUtility.CurveModifiedType.CurveDeleted : AnimationUtility.CurveModifiedType.CurveModified);
			}
		}
Exemplo n.º 5
0
 private static void AddSpriteAnimationToClip(AnimationClip newClip, UnityEngine.Object[] frames)
 {
     newClip.frameRate = 12f;
     ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frames.Length];
     for (int i = 0; i < keyframes.Length; i++)
     {
         keyframes[i] = new ObjectReferenceKeyframe();
         keyframes[i].value = RemapObjectToSprite(frames[i]);
         keyframes[i].time = ((float) i) / newClip.frameRate;
     }
     EditorCurveBinding binding = EditorCurveBinding.PPtrCurve(string.Empty, typeof(SpriteRenderer), "m_Sprite");
     AnimationUtility.SetObjectReferenceCurve(newClip, binding, keyframes);
 }
Exemplo n.º 6
0
        private static void AddSpriteAnimationToClip(AnimationClip newClip, Object[] frames)
        {
            newClip.frameRate = 12f;
            ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frames.Length];
            for (int i = 0; i < keyframes.Length; i++)
            {
                keyframes[i]       = new ObjectReferenceKeyframe();
                keyframes[i].value = RemapObjectToSprite(frames[i]);
                keyframes[i].time  = ((float)i) / newClip.frameRate;
            }
            EditorCurveBinding binding = EditorCurveBinding.PPtrCurve(string.Empty, typeof(SpriteRenderer), "m_Sprite");

            AnimationUtility.SetObjectReferenceCurve(newClip, binding, keyframes);
        }
Exemplo n.º 7
0
        private static void AddSpriteAnimationToClip(AnimationClip newClip, UnityEngine.Object[] frames)
        {
            newClip.frameRate = 12f;
            ObjectReferenceKeyframe[] array = new ObjectReferenceKeyframe[frames.Length];
            for (int i = 0; i < array.Length; i++)
            {
                array[i]       = default(ObjectReferenceKeyframe);
                array[i].value = SpriteUtility.RemapObjectToSprite(frames[i]);
                array[i].time  = (float)i / newClip.frameRate;
            }
            EditorCurveBinding binding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite");

            AnimationUtility.SetObjectReferenceCurve(newClip, binding, array);
        }
Exemplo n.º 8
0
        private static void AddSpriteAnimationToClip(AnimationClip newClip, UnityEngine.Object[] frames)
        {
            newClip.frameRate = 12f;
            ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frames.Length];
            for (int index = 0; index < keyframes.Length; ++index)
            {
                keyframes[index]       = new ObjectReferenceKeyframe();
                keyframes[index].value = (UnityEngine.Object)SpriteUtility.RemapObjectToSprite(frames[index]);
                keyframes[index].time  = (float)index / newClip.frameRate;
            }
            EditorCurveBinding binding = EditorCurveBinding.PPtrCurve(string.Empty, typeof(SpriteRenderer), "m_Sprite");

            AnimationUtility.SetObjectReferenceCurve(newClip, binding, keyframes);
        }
    AnimationClip createAnimationClip(params Sprite[] sprites)
    {
        AnimationClip clip = new AnimationClip { frameRate = 9 };
        AnimationClipSettings setting = new AnimationClipSettings { loopTime = true };
        AnimationUtility.SetAnimationClipSettings(clip, setting);
        ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[sprites.Length];
        for (int i = 0; i < keyframes.Length; i++) {
            keyframes[i] = new ObjectReferenceKeyframe {
                value = sprites[i],
                time = i / clip.frameRate
            };
        }

        EditorCurveBinding curvebinding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite");
        AnimationUtility.SetObjectReferenceCurve(clip, curvebinding, keyframes);
        return clip;
    }
        private static ObjectReferenceKeyframe[] CreateKeysForSprites(Sprite[] sprites, int samplesPerSecond)
        {
            List<ObjectReferenceKeyframe> keys = new List<ObjectReferenceKeyframe>();
            float timePerFrame = 1.0f / samplesPerSecond;
            float currentTime = 0.0f;
            foreach (Sprite sprite in sprites)
            {
                ObjectReferenceKeyframe keyframe = new ObjectReferenceKeyframe();
                keyframe.time = currentTime;
                keyframe.value = sprite;
                keys.Add(keyframe);

                currentTime += timePerFrame;
            }

            return keys.ToArray();
        }
Exemplo n.º 11
0
        /**
         * make animation fróm a list of sprites
         */
        public static AnimationClip CreateSpriteAnimationClip(string name, List<Sprite> sprites, int fps, bool raiseEvent = false)
        {
            int framecount = sprites.Count;
            float frameLength = 1f / 30f;

            AnimationClip clip = new AnimationClip();
            clip.frameRate = fps;

            AnimationUtility.GetAnimationClipSettings(clip).loopTime = true;

            EditorCurveBinding curveBinding = new EditorCurveBinding();
            curveBinding.type = typeof(SpriteRenderer);
            curveBinding.propertyName = "m_Sprite";

            // set animation keys
            ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[framecount];

            for (int i = 0; i < framecount; i++)
            {
                ObjectReferenceKeyframe kf = new ObjectReferenceKeyframe();
                kf.time = i * frameLength;
                kf.value = sprites[i];
                keyFrames[i] = kf;
            }

            clip.name = name;

            //AnimationUtility.SetAnimationType(clip, ModelImporterAnimationType.Generic);
            //if (name != "Fall")
            Debug.Log(clip.wrapMode);
            clip.wrapMode = WrapMode.Once;
            //setAnimationLoop(clip);
            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);

            //clip.ValidateIfRetargetable(true);

            if (raiseEvent)
            {
                //AnimationUtility.SetAnimationEvents(clip, new[] { new AnimationEvent() { time = clip.length, functionName = "on" + name } });
            }
            //clip.AddEvent(e);
            return clip;
        }
Exemplo n.º 12
0
    static AnimationClip BuildAnimationClip(DirectoryInfo dictorys)
    {
        string animationName = dictorys.Name;
        //查找所有png图片
        FileInfo []images  = dictorys.GetFiles("*.png");
        AnimationClip clip = new AnimationClip();
           //过时函数     AnimationUtility.SetAnimationType(clip, ModelImporterAnimationType.Generic);
        EditorCurveBinding curveBinding = new EditorCurveBinding();
        curveBinding.type = typeof(SpriteRenderer);
        curveBinding.path="";
        curveBinding.propertyName = "m_Sprite";
        ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[images.Length];
        //动画长度是按秒为单位,1/10就表示1秒切10张图片
        float frameTime = 1/10f;
        for(int i =0; i< images.Length; i++){
            Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(DataPathToAssetPath(images[i].FullName));
            keyFrames[i] =   new ObjectReferenceKeyframe ();
            keyFrames[i].time = frameTime *i;
            keyFrames[i].value = sprite;
        }
        //动画帧率
        clip.frameRate = 30;

        //动画循环
        if(animationName.IndexOf("idle") >=0 )
        {
            //设置idle文件为循环动画
            SerializedObject serializedClip = new SerializedObject(clip);
            AnimationClipSettings clipSettings = new AnimationClipSettings(serializedClip.FindProperty("m_AnimationClipSettings"));
            clipSettings.loopTime = true;
            serializedClip.ApplyModifiedProperties();
        }
        string parentName = System.IO.Directory.GetParent(dictorys.FullName).Name;
        if (!Directory.Exists(AnimationPath + "/" + parentName))
        {
            System.IO.Directory.CreateDirectory(AnimationPath + "/" + parentName);
        }
        AnimationUtility.SetObjectReferenceCurve(clip,curveBinding,keyFrames);
        AssetDatabase.CreateAsset(clip,AnimationPath +"/"+parentName +"/" +animationName+".anim");
        AssetDatabase.SaveAssets();
        return clip;
    }
Exemplo n.º 13
0
        static void AddSpriteAnimationToClip(AnimationClip newClip, Object[] frames)
        {
            // TODO Default framerate be exposed to user?
            newClip.frameRate = 12;

            // Add keyframes
            ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frames.Length];

            for (int i = 0; i < keyframes.Length; i++)
            {
                keyframes[i]       = new ObjectReferenceKeyframe();
                keyframes[i].value = RemapObjectToSprite(frames[i]);
                keyframes[i].time  = i / newClip.frameRate;
            }

            // Create binding
            EditorCurveBinding curveBinding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite");

            // Save curve to clip
            AnimationUtility.SetObjectReferenceCurve(newClip, (EditorCurveBinding)curveBinding, keyframes);
        }
Exemplo n.º 14
0
    //将图集生成动画文件
    private static AnimationClip BuildAnimationClip(DirectoryInfo dictoryAnimations)
    {
        string animationName = dictoryAnimations.Name;
        FileInfo[] images = dictoryAnimations.GetFiles("*." + imageFormat);
        AnimationClip clip = new AnimationClip();
        AnimationUtility.SetAnimationType(clip, ModelImporterAnimationType.Generic); //设置动画类型
        EditorCurveBinding curveBinding = new EditorCurveBinding();
        curveBinding.type = typeof (SpriteRenderer);
        curveBinding.path = "";
        curveBinding.propertyName = "m_Sprite";
        ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[images.Length];

        for (int i = 0; i < images.Length; i++)
        {
            Sprite sprite = Resources.LoadAssetAtPath<Sprite>(DataPathToAssetPath(images[i].FullName));
            keyFrames[i] = new ObjectReferenceKeyframe();
            keyFrames[i].time = frameTime*i;
            keyFrames[i].value = sprite;
        }
        clip.frameRate = frameRate;
        if (animationName.IndexOf("idle") >= 0)
        {
            //设置idle动画为循环动画
            SerializedObject serializedClip = new SerializedObject(clip);
            AnimationClipSettings clipSettings =
                new AnimationClipSettings(serializedClip.FindProperty("m_AnimationClipSettings"));
            clipSettings.loopTime = true;
            serializedClip.ApplyModifiedProperties();
        }

        string parentName = System.IO.Directory.GetParent((dictoryAnimations.FullName)).Name;
        System.IO.Directory.CreateDirectory(animationPath + "/" + parentName);
        AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);
        AssetDatabase.CreateAsset(clip, animationPath + "/" + parentName + "/" + animationName + ".anim");
        AssetDatabase.SaveAssets();
        return clip;
    }
Exemplo n.º 15
0
        /// <summary>
        /// Adds the keyframe to object reference curve.
        /// </summary>
        /// <param name="keyframes">Keyframes.</param>
        /// <param name="animatedClip">Animated clip.</param>
        /// <param name="binding">Binding.</param>
        /// <param name="value">Value.</param>
        /// <param name="type">Type.</param>
        /// <param name="time">Time.</param>
        public static void AddKeyframeToObjectReferenceCurve(ObjectReferenceKeyframe[] keyframes, AnimationClip animatedClip, EditorCurveBinding binding, object value, Type type, float time)
        {
            int keyframeIndex = Array.FindIndex (keyframes, (itm) => (int)itm.time * animatedClip.frameRate == (int)time * animatedClip.frameRate);

                        //no keyframe found
                        if (keyframeIndex < 0) {
                                List<ObjectReferenceKeyframe> list = keyframes.ToList ();

                                ObjectReferenceKeyframe objectReferenceKeyframe = default(ObjectReferenceKeyframe);
                                objectReferenceKeyframe.time = time;
                                objectReferenceKeyframe.value = value as UnityEngine.Object;
                                list.Add (objectReferenceKeyframe);

                                keyframes = list.ToArray ();

                        } else {
                                //??? maybe I should add new time too
                                keyframes [keyframeIndex].value = value as UnityEngine.Object;

                        }

                        //save
                        AnimationUtility.SetObjectReferenceCurve (animatedClip, binding, keyframes);
        }
Exemplo n.º 16
0
 private static void Internal_SetObjectReferenceCurve(AnimationClip clip, EditorCurveBinding binding, ObjectReferenceKeyframe[] keyframes)
 {
     INTERNAL_CALL_Internal_SetObjectReferenceCurve(clip, ref binding, keyframes);
 }
Exemplo n.º 17
0
        private void BuildSpriteChangeCurve(ref AnimationClip clip, KeyValuePair<string, List<SpriteChangeKey>> timeline)
        {
            // First you need to create Editor Curve Binding
            EditorCurveBinding curveBinding = new EditorCurveBinding();

            // I want to change the sprites of the sprite renderer, so I put the typeof(SpriteRenderer) as the binding type.
            curveBinding.type = typeof(SpriteRenderer);

            // Regular path to the GameObject that will be changed
            curveBinding.path = timeline.Key;

            // This is the property name to change the sprite of a sprite renderer
            curveBinding.propertyName = "m_Sprite";

            // An array to hold the object keyframes
            ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[timeline.Value.Count];

            int i = 0;
            foreach (var key in timeline.Value)
            {
                keyFrames[i] = new ObjectReferenceKeyframe();
                // set the time
                keyFrames[i].time = key.Time;
                // set reference for the sprite you want
                keyFrames[i].value = key.Sprite;
                i++;

            }

            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);
        }
Exemplo n.º 18
0
    public AnimationClip CreateClip(Object obj, string clipName, int startFrame, int endFrame,
	                                float frameRate, float timeBetween, bool pingPong)
    {
        // Get path to the object
        string path = AssetDatabase.GetAssetPath(obj);

        // Extract the sprites
        Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path);

        // Determine how many frames, and the length of each frame
        int frameCount = endFrame - startFrame + 1;
        float frameLength = 1f / timeBetween;

        // Create a new (empty) animation clip
        AnimationClip clip = new AnimationClip();

        // Set the framerate for the clip
        clip.frameRate = frameRate;

        // Create the new (empty) curve binding
        EditorCurveBinding curveBinding = new EditorCurveBinding();
        // Assign it to change the sprite renderer
        curveBinding.type = typeof(SpriteRenderer);
        // Assign it to alter the sprite of the sprite renderer
        curveBinding.propertyName = "m_Sprite";

        // Create a container for all of the keyframes
        ObjectReferenceKeyframe[] keyFrames;

        // Determine how many frames there will be if we are or are not pingponging
        if (!pingPong)
            keyFrames = new ObjectReferenceKeyframe[frameCount + 1];
        else
            keyFrames = new ObjectReferenceKeyframe[frameCount * 2 + 1];

        // Keep track of what frame number we are on
        int frameNumber = 0;

        // Loop from start to end, incrementing frameNumber as we go
        for (int i = startFrame; i < endFrame + 1; i++, frameNumber++)
        {
            // Create an empty keyframe
            ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();
            // Assign it a time to appear in the animation
            tempKeyFrame.time = frameNumber * frameLength;
            // Assign it to a sprite
            tempKeyFrame.value = sprites[i];
            // Place it into the container for all the keyframes
            keyFrames[frameNumber] = tempKeyFrame;
        }

        // If we are pingponging this animation
        if (pingPong)
        {
            // Create keyframes starting at the end and going backwards
            // Continue to keep track of the frame number
            for (int i = endFrame; i >= startFrame; i--, frameNumber++)
            {
                ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();
                tempKeyFrame.time = frameNumber * frameLength;
                tempKeyFrame.value = sprites[i];
                keyFrames[frameNumber] = tempKeyFrame;
            }
        }

        // Create the last sprite to stop it from switching quickly from the last frame to the first one
        ObjectReferenceKeyframe lastSprite = new ObjectReferenceKeyframe();
        lastSprite.time = frameNumber * frameLength;
        lastSprite.value = sprites[startFrame];
        keyFrames[frameNumber] = lastSprite;

        // Assign the name
        clip.name = clipName;

        // Apply the curve
        AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);

        // Create the clip
        AssetDatabase.CreateAsset(clip, ("Assets/" + clipName + ".anim"));

        // Return the clip
        return clip;
    }
Exemplo n.º 19
0
    AnimationClip GenerateAnimation(string name, int frameRate, int frameNo, int frameCount)
    {
        AnimationClip animationClip = new AnimationClip();
        animationClip.name = name;
        animationClip.frameRate = frameRate;
        //		AnimationUtility.SetAnimationType(animationClip, ModelImporterAnimationType.Generic);

        EditorCurveBinding curveBinding = new EditorCurveBinding();

        curveBinding.type = typeof(SpriteRenderer);
        curveBinding.path = "";
        curveBinding.propertyName = "m_Sprite";

        ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frameCount];
        for (int i=0; i<frameCount; i++) {
            keyframes[i] = new ObjectReferenceKeyframe();
            keyframes[i].time = (float)i / frameRate;
            keyframes[i].value = sortedFrames[frameNo + i];
        }

        if (frameCount == 4) {
            keyframes[3].value = sortedFrames[frameNo + 1];
        }

        AnimationUtility.SetObjectReferenceCurve(animationClip, curveBinding, keyframes);

        Debug.Log("New animation generated.");
        return animationClip;
    }
Exemplo n.º 20
0
 /// <summary>
 /// Clip生成実体
 /// </summary>
 /// <param name="sprites">各フレームに割り当てるSpriteの配列</param>
 AnimationClip CreateAnimationClip(params Sprite[] sprites)
 {
     /// Copyright (c) 2015 kyusyukeigo
     /// Released under the MIT license
     /// https://github.com/anchan828/unite2015tokyo/blob/master/LICENSE
     
     var animationClip = new AnimationClip { frameRate = 12 };
     var animationClipSettings = new AnimationClipSettings { loopTime = true };
     AnimationUtility.SetAnimationClipSettings(animationClip, animationClipSettings);
     var objectReferenceKeyframes = new ObjectReferenceKeyframe[sprites.Length];
     for (var i = 0; i < objectReferenceKeyframes.Length; i++)
     {
         objectReferenceKeyframes[i] = new ObjectReferenceKeyframe
         {
             value = sprites[i],
             time = i / animationClip.frameRate
         };
     }
     var editorCurveBinding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite");
     AnimationUtility.SetObjectReferenceCurve(animationClip, editorCurveBinding, objectReferenceKeyframes);
     return animationClip;
 }
Exemplo n.º 21
0
 private static extern void Internal_SetObjectReferenceCurve(AnimationClip clip, EditorCurveBinding binding, ObjectReferenceKeyframe[] keyframes);
    public void OnGUI()
    {
        // Make sure there is at least one animation clip selected
        if (animationClips.Count > 0 ) {
            scrollPos = GUILayout.BeginScrollView(scrollPos, GUIStyle.none);

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Animation Clip:", GUILayout.Width(columnWidth));

            if ( animationClips.Count == 1 )
            {
                animationClips[0] = ((AnimationClip)EditorGUILayout.ObjectField(
                    animationClips[0],
                    typeof(AnimationClip),
                    true,
                    GUILayout.Width(columnWidth))
                    );
            }
            else
            {
                GUILayout.Label("Multiple Anim Clips: " + animationClips.Count, GUILayout.Width(columnWidth));
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(20);

            EditorGUILayout.BeginHorizontal();

            EditorGUILayout.LabelField ("Sprites:");

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();

            GUILayout.Label("Original Sprite Text:", GUILayout.Width(columnWidth));
            GUILayout.Label("Replacement Sprite Text:", GUILayout.Width(columnWidth));

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            originalSpriteText = EditorGUILayout.TextField(originalSpriteText, GUILayout.Width(columnWidth));
            replaceSpriteText = EditorGUILayout.TextField(replaceSpriteText, GUILayout.Width(columnWidth));
            if (GUILayout.Button("Replace All Sprites")) {
                changeAllSprites = true;
            }

            EditorGUILayout.EndHorizontal();

            // Iterate through the animation clips
            foreach (AnimationClip clip in animationClips) {

                // Iterate through the bindings for the current animation clip
                foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings (clip))
                {
                    // If the binding is a sprite type then get the keyframes
                    if (binding.propertyName == "m_Sprite") {
                        // Get the keyframes for this sprite
                        ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve (clip, binding);
                        // Show the sprite's path and the keyframes length for this binding
                        EditorGUILayout.LabelField (binding.path + "/" + binding.propertyName + ", Keys: " + keyframes.Length);

                        // Loop through the keyframes to change the sprite
                        for (int i = 0; i < keyframes.Length; i++) {
                            // If the button is pushed then change the sprite
                            if (changeAllSprites) {
                                // The keyframe's value is the sprite
                                Sprite keyframeSprite = (Sprite)keyframes[i].value;
                                // If the sprite exists get the name of the sprite
                                if (keyframeSprite != null) {
                                    string spriteName = keyframeSprite.name;
                                    // Replace the text in the sprite's name to the replacement text
                                    string newSpriteName = spriteName.Replace(originalSpriteText, replaceSpriteText);
                                    Debug.Log(newSpriteName);

                                    // Get all the sprites in the project
                                    GetAllSprites();

                                    // Make sure we have at least one sprite
                                    if (sprites.Length > 0) {
                                        // Loop through all the sprites to get the one matching the new sprite name
                                        foreach (Sprite sprite in sprites) {
                                            if (sprite != null && sprite.name == newSpriteName) {
                                                // Cache the time for this keyframe
                                                float timeForKey = keyframes[i].time;
                                                // Create a new ObjectReferenceKeyframe for the sprite
                                                keyframes[i] = new ObjectReferenceKeyframe();
                                                // set the time
                                                keyframes[i].time = timeForKey;
                                                // set reference for the sprite you want
                                                keyframes[i].value = sprite;
                                                // Set the new keyframes to the binding of the animation clip
                                                AnimationUtility.SetObjectReferenceCurve(clip, binding, keyframes);
                                                Debug.Log("Sprite changed to " + sprite.name);
                                                // Break the loop since we already found it
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            // Show the sprite in the editor window
                            EditorGUILayout.ObjectField (keyframes[i].value, typeof (Sprite), false);
                        }
                    }
                }
            }
            // Reset the button if pushed
            changeAllSprites = false;
            GUILayout.Space(40);
            GUILayout.EndScrollView();
        } else {
            GUILayout.Label("Please select an Animation Clip");
        }
    }
Exemplo n.º 23
0
    //Creates the animation
    public AnimationClip CreateClip(Object obj, string clipName, int startFrame, int endFrame, float frameRate, float timeBetween, bool pingPong)
    {
        string path = AssetDatabase.GetAssetPath(obj);

        Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path);

        int frameCount = endFrame - startFrame + 1;
        float frameLength = 1f / timeBetween;

        AnimationClip clip = new AnimationClip();

        clip.frameRate = frameRate;

        EditorCurveBinding curveBinding = new EditorCurveBinding();
        curveBinding.type = typeof(SpriteRenderer);
        curveBinding.propertyName = "m_Sprite";

        ObjectReferenceKeyframe[] keyFrames;

        if (!pingPong)
        {
            keyFrames = new ObjectReferenceKeyframe[frameCount + 1];
        }
        else
        {
            keyFrames = new ObjectReferenceKeyframe[frameCount * 2 + 1];
        }

        int frameNumber = 0;

        for (int i = startFrame; i < endFrame + 1; i++, frameNumber++)
        {
            ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();
            tempKeyFrame.time = frameNumber * frameLength;
            tempKeyFrame.value = sprites[i];
            keyFrames[frameNumber] = tempKeyFrame;
        }

        //sets up ping pong behaviour
        if (pingPong)
        {
            for (int i = endFrame; i >= startFrame; i--, frameNumber++)
            {
                ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();
                tempKeyFrame.time = frameNumber * frameLength;
                tempKeyFrame.value = sprites[i];
                keyFrames[frameNumber] = tempKeyFrame;
            }
        }

        ObjectReferenceKeyframe lastSprite = new ObjectReferenceKeyframe();
        lastSprite.time = frameNumber * frameLength;
        lastSprite.value = sprites[startFrame];
        keyFrames[frameNumber] = lastSprite;

        clip.name = clipName;

        AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);

        //Creates the animation asset inside of the Animations folder
        AssetDatabase.CreateAsset(clip, ("Assets/" + clipName + ".anim"));

        return clip;
    }
    public AnimationClip CreateClip(Object obj, string clipName, int startFrame, int endFrame, float frameRate, float timeBetween, bool pingPong)
    {
        //Get the path to the object
        string path = AssetDatabase.GetAssetPath(obj);

        //Extract the sprites
        Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path);

        if (endFrame <= sprites.Length & startFrame <= endFrame)
        {
            //Determine number of frames and frame length
            int frameCount = endFrame - startFrame + 1;
            float frameLength = 1f / timeBetween;

            //Create new clip and initialize frame rate
            AnimationClip clip = new AnimationClip();
            clip.frameRate = frameRate;

            //Create the new curve binding and set it to change the sprite of the sprite renderer
            EditorCurveBinding curveBinding = new EditorCurveBinding();
            curveBinding.type = typeof(SpriteRenderer);
            curveBinding.propertyName = "m_Sprite";

            //Create a container for the key frames
            ObjectReferenceKeyframe[] keyFrames;

            //Determine if we are ping ponging or not
            if (pingPong)
            {
                keyFrames = new ObjectReferenceKeyframe[frameCount * 2 + 1];
            }
            else
            {
                keyFrames = new ObjectReferenceKeyframe[frameCount + 1];
            }

            //Keep track of what frame number we are on
            int frameNumber = 0;

            //Loop from start to finish of the animation
            for (int i = startFrame; i < endFrame; i++, frameNumber++)
            {
                //Create a new keyframe
                ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();

                //Assign it a time to appear in the animation
                tempKeyFrame.time = frameNumber * frameLength;

                //Assign it a sprite
                tempKeyFrame.value = sprites[i];

                //Place it in the container for all the keyframes
                keyFrames[frameNumber] = tempKeyFrame;
            }

            //If we are pingponging
            if (pingPong)
            {
                //Create keyframes starting at the end and going backwards
                //Continue to keep track of the frame number
                for (int i = endFrame; i > startFrame; i--, frameNumber++)
                {
                    //Create a new keyframe
                    ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();

                    //Assign it a time to appear in the animation
                    tempKeyFrame.time = frameNumber * frameLength;

                    //Assign it a sprite
                    tempKeyFrame.value = sprites[i];

                    //Place it in the container for all the keyframes
                    keyFrames[frameNumber] = tempKeyFrame;
                }
            }

            //Create the last keyframe to stop the loop from not really displaying the final frame
            ObjectReferenceKeyframe lastSprite = new ObjectReferenceKeyframe();
            lastSprite.time = frameNumber * frameLength;
            lastSprite.value = sprites[startFrame];
            keyFrames[frameNumber] = lastSprite;

            //Assign the name
            clip.name = clipName;

            //Apply the curve
            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);

            //Create the clip
            AssetDatabase.CreateAsset(clip, (@"Assets/" + clipName + ".anim"));
            return clip;
        }
        else
        {
            return null;
        }
    }
Exemplo n.º 25
0
    /**
     * AnimationClip creates a 2D sprite animation.
     *
     * @param obj: Spritesheet to build animation from
     * @param slipName: animation name
     * @param startFrame: first frame of animation
     * @param endFrame: last frame of animation
     * @param frameRate: time to transition between frames
     * @param timeBetweem: delay time for frame transitions
     * @param pingPong: flag for determining if animation will ping-pong
     *
     * @return: Returns a 2D sprite animation clip
     */
    public AnimationClip CreateClip(Object obj, string clipName, int startFrame, int endFrame, float frameRate, float timeBetween, bool pingPong)
    {
        // Get animation information: animation location (via its filepath) and all sprites
        string path = AssetDatabase.GetAssetPath(obj);
        Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path);

        // Determine frame information
        int frameCount = endFrame - startFrame + 1;
        float frameLength = 1f / timeBetween;

        AnimationClip clip = new AnimationClip();
        clip.frameRate = frameRate;

        // Create a curve binding
        EditorCurveBinding curveBinding = new EditorCurveBinding();
        // Make the binding change the sprite renderer
        curveBinding.type = typeof(SpriteRenderer); // This code seems obsolete in Unity 5; sprites fail to render in Editor.
        curveBinding.propertyName = "m_Sprite";
        // Create an animation keyframes container
        ObjectReferenceKeyframe[] keyframes;
        // Determine number of keyframes based on ping-ponging
        if (!pingPong)
            keyframes = new ObjectReferenceKeyframe[frameCount + 1];
        else
            keyframes = new ObjectReferenceKeyframe[frameCount * 2 + 1];

        // Initialize frameNumber
        int frameNumber = 0;

        // Add keyframes
        for (int i = startFrame; i < endFrame + 1; i++, frameNumber++)
        {
            ObjectReferenceKeyframe tempFrame = new ObjectReferenceKeyframe();
            tempFrame.time = frameNumber * frameLength;
            tempFrame.value = sprites[i];
            keyframes[frameNumber] = tempFrame;
        }
        // Double the frames if ping-ponging
        if (pingPong)
        {
            for (int i = endFrame; i >= startFrame; i--, frameNumber--)
            {
                ObjectReferenceKeyframe tempFrame = new ObjectReferenceKeyframe();
                tempFrame.time = frameNumber * frameLength;
                tempFrame.value = sprites[i];
                keyframes[frameNumber] = tempFrame;
            }
        }

        // Create the final frame
        ObjectReferenceKeyframe lastSprite = new ObjectReferenceKeyframe();
        lastSprite.time = frameNumber * frameLength;
        lastSprite.value = sprites[startFrame];
        keyframes[frameNumber] = lastSprite;

        // Finalize clip properties
        clip.name = clipName;
        AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyframes);
        // Create and return the animation clip
        AssetDatabase.CreateAsset(clip, ("Assets/" + clipName + ".anim"));
        return clip;
    }
Exemplo n.º 26
0
    void OnGUI()
    {
        EditorGUILayout.LabelField("一个角色的切好的Sprite(任选一个)");
        spritesheet = EditorGUILayout.ObjectField(spritesheet, typeof(Sprite), false) as Sprite;
        EditorGUILayout.LabelField("每个Walk动画的帧数");
        iFramesPerLoop = EditorGUILayout.IntField(iFramesPerLoop);
        EditorGUILayout.LabelField("Sprite中总共动画个数");
        iTotalLoops = EditorGUILayout.IntField(iTotalLoops);
        bMirrorLR234 = EditorGUILayout.ToggleLeft("第2,3,4个动画生成左右对称的两个动画", bMirrorLR234);
        bIdleForLoop = EditorGUILayout.ToggleLeft("给每个动画创建一个Idle动画", bIdleForLoop);
        EditorGUILayout.LabelField("Idle动画单帧位于每个动画中的位置(从1开始)");
        iIdleFrameForLoop = EditorGUILayout.IntField(iIdleFrameForLoop);
        EditorGUILayout.LabelField("每秒帧数(Samples)");
        iSamples = EditorGUILayout.IntField(iSamples);

        if (GUILayout.Button("载入生成"))
        {
            string sheetPath = AssetDatabase.GetAssetPath(spritesheet);
            //Assets/Resources/Sprites/Character/chara_01.png
            characterName = Path.GetFileNameWithoutExtension(sheetPath);
            //chara_01
            directory = Path.GetDirectoryName(sheetPath);
            //Assets/Resources/Sprites/Character/

            sprites = AssetDatabase.LoadAllAssetsAtPath(sheetPath).OfType<Sprite>().ToArray();

            if (!bMirrorLR234)
            {
                //原本的代码
                for (int i = 0; i < iTotalLoops; i++)
                {
                    AnimationClip clip = new AnimationClip();
                    clip.frameRate = iFramesPerLoop;

                    EditorCurveBinding curveBinding = new EditorCurveBinding();
                    curveBinding.path = "";
                    curveBinding.propertyName = "m_Sprite";
                    curveBinding.type = typeof(SpriteRenderer);

                    ObjectReferenceKeyframe[] keys = new ObjectReferenceKeyframe[iFramesPerLoop];
                    for (int j = 0; j < iFramesPerLoop; j++)
                    {
                        keys[j] = new ObjectReferenceKeyframe();
                        keys[j].time = (1.0f / iFramesPerLoop) * j;
                        keys[j].value = sprites[iFramesPerLoop * i + j];
                    }

                    AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keys);
                    AssetDatabase.CreateAsset(clip, directory + "/" + characterName + "_" + clipNames[i] + ".anim");
                }
            }
            else
            {
                //234要生成镜像的代码
                for (int i = 0; i < iTotalLoops + 3; i++)
                {
                    int targetKey;
                    targetKey = (i + 1) / 2;
                    //0 1 2 3 4 5 6 7
                    //covert to
                    //0 1 1 2 2 3 3 4

                    AnimationClip clip = new AnimationClip();
                    clip.frameRate = iSamples;

                    EditorCurveBinding curveBinding = new EditorCurveBinding();
                    curveBinding.path = "";
                    curveBinding.propertyName = "m_Sprite";
                    curveBinding.type = typeof(SpriteRenderer);

                    ObjectReferenceKeyframe[] keys = new ObjectReferenceKeyframe[iFramesPerLoop + 1];
                    for (int j = 0; j < iFramesPerLoop; j++)
                    {
                        keys[j] = new ObjectReferenceKeyframe();
                        keys[j].time = (1.0f / iSamples) * j;
                        keys[j].value = sprites[iFramesPerLoop * targetKey + j];
                    }
                    keys[3] = new ObjectReferenceKeyframe();
                    keys[3].time = (1.0f / iSamples) * 3;
                    keys[3].value = sprites[iFramesPerLoop * targetKey + 1];

                    switch (i)
                    {
                        case 2:
                        case 4:
                        case 6:
                            EditorCurveBinding cb2 = new EditorCurveBinding();
                            cb2.path = "";
                            cb2.propertyName = "m_FlipX";
                            cb2.type = typeof(SpriteRenderer);
                            AnimationCurve ac = new AnimationCurve();
                            ac.AddKey(0f, 1f);
                            AnimationUtility.SetEditorCurve(clip, cb2, ac);
                            Debug.Log(i);
                            break;
                    }


                    AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keys);
                    AssetDatabase.CreateAsset(clip, directory + "/" + characterName + "_" + clipNames[i] + ".anim");
                }
                if (bIdleForLoop)
                {
                    for (int i = 0; i < iTotalLoops + 3; i++)
                    {
                        int targetKey;
                        targetKey = (i + 1) / 2;
                        //0 1 2 3 4 5 6 7
                        //covert to
                        //0 1 1 2 2 3 3 4

                        AnimationClip clip = new AnimationClip();
                        clip.frameRate = iSamples;

                        EditorCurveBinding curveBinding = new EditorCurveBinding();
                        curveBinding.path = "";
                        curveBinding.propertyName = "m_Sprite";
                        curveBinding.type = typeof(SpriteRenderer);

                        ObjectReferenceKeyframe[] keys = new ObjectReferenceKeyframe[1];
                        keys[0] = new ObjectReferenceKeyframe();
                        keys[0].time = 0f;
                        keys[0].value = sprites[iFramesPerLoop * targetKey + 1];
                        switch (i)
                        {
                            case 2:
                            case 4:
                            case 6:
                                EditorCurveBinding cb2 = new EditorCurveBinding();
                                cb2.path = "";
                                cb2.propertyName = "m_FlipX";
                                cb2.type = typeof(SpriteRenderer);
                                AnimationCurve ac = new AnimationCurve();
                                ac.AddKey(0f, 1f);
                                AnimationUtility.SetEditorCurve(clip, cb2, ac);
                                Debug.Log(i);
                                break;
                        }

                        AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keys);
                        AssetDatabase.CreateAsset(clip, directory + "/" + characterName + "_" + clipNamesIdle[i] + "_Idle.anim");
                    }
                }
            }
            string[] folders = new string[1];
            folders[0] = directory;
            string[] clipPaths = AssetDatabase.FindAssets(characterName, folders);

            List<AnimationClip> clips = new List<AnimationClip>();
            for (int i = 0; i < clipPaths.Length; i++)
            {
                AnimationClip c = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(clipPaths[i]), typeof(AnimationClip)) as AnimationClip;
                if (c != null)
                    clips.Add(c);
            }

            for (int i = 0; i < clips.Count; i++)
            {
                SerializedObject serializedClip = new SerializedObject(clips[i]);
                AnimationClipSettings clipSettings = new AnimationClipSettings(serializedClip.FindProperty("m_AnimationClipSettings"));

                clipSettings.loopTime = true;

                serializedClip.ApplyModifiedProperties();
            }

            AnimatorController controller = AnimatorController.CreateAnimatorControllerAtPath(directory + "/" + characterName + "_AnimatorController.controller");
            controller.AddParameter("X", AnimatorControllerParameterType.Float);
			controller.AddParameter("Y", AnimatorControllerParameterType.Float);

			BlendTree tree;
            controller.CreateBlendTreeInController("Walk", out tree, 0);
			tree.blendType = BlendTreeType.SimpleDirectional2D;
            tree.blendParameter = "X";
			tree.blendParameterY = "Y";
            tree.useAutomaticThresholds = false;
			int cc = (bIdleForLoop ? clips.Count / 2 : clips.Count);
			for (int i = 0; i < cc; i++) 
            {
				double d = i * Mathf.PI * 2 / cc;
				float x, y;
				y = (float)System.Math.Cos(d);
				x = (float)System.Math.Sin(d);
				tree.AddChild(clips[i], new Vector2(x, y));
            }

            GameObject go = GameObject.Find(characterName);
            if (go == null)
            {
                go = new GameObject(characterName);
                go.AddComponent<SpriteRenderer>().sprite = sprites[0];
                go.AddComponent<Animator>().runtimeAnimatorController = controller;
            }
            else
            {
                SpriteRenderer sr = go.GetComponent<SpriteRenderer>();
                if (sr == null)
                    go.AddComponent<SpriteRenderer>().sprite = sprites[0];
                else
                    sr.sprite = sprites[0];

                Animator anim = go.GetComponent<Animator>();
                if (anim == null)
                    go.AddComponent<Animator>().runtimeAnimatorController = controller;
                else
                    anim.runtimeAnimatorController = controller;
            }

            PrefabUtility.CreatePrefab(directory + "/" + characterName + ".prefab", go);
        }

    }
Exemplo n.º 27
0
    private void Run()
    {
        string fileData = File.ReadAllText (json_location);
        JSONObject data = new JSONObject (fileData);

        Uri assetsPath = new Uri (Application.dataPath);
        Uri jsonPath = new Uri (System.IO.Path.GetDirectoryName (json_location));
        Uri diff = assetsPath.MakeRelativeUri (jsonPath);
        string wd = diff.OriginalString+System.IO.Path.DirectorySeparatorChar;

        //test data
        if(!data.HasFields(new string[]{"framerate","images","frames","animations"}))
        {
            Debug.LogError("Error: json file must contain framerate, images, frames, and animations.");
            return;
        }

        //generate sprite frames
        List<JSONObject> frames_data = data.GetField ("frames").list;
        List<JSONObject> images_data = data.GetField ("images").list;

        // load textures
        List<Texture2D> images = new List<Texture2D>();
        List<List<SpriteMetaData>> sprite_metadata = new List<List<SpriteMetaData>> ();
        for(int i=0; i<images_data.Count; i++)
        {
            string path = wd+images_data[i].str;
            Texture2D tex = AssetDatabase.LoadMainAssetAtPath(path) as Texture2D;
            images.Add(tex);
            sprite_metadata.Add (new List<SpriteMetaData> ());
        }

        //set meta data based on frames
        for(int i=0; i<frames_data.Count; i++)
        {
            List<JSONObject> frame = frames_data[i].list;
            float x = frame[0].f;
            float y = frame[1].f;
            float w = frame[2].f;
            float h = frame[3].f;
            int img = (int)frame[4].f;
            float rx = frame[5].f;
            float ry = frame[6].f;

            float imgHeight = (float)images[img].height;

            SpriteMetaData meta = new SpriteMetaData{
                alignment = (int)SpriteAlignment.Custom,
                border = new Vector4(),
                name = prefix+"_"+(i).ToString(),
                pivot = new Vector2(rx/w,1-(ry/h)),
                rect = new Rect(x, imgHeight - y - h, w, h)
            };
            sprite_metadata[img].Add(meta);
        }

        //save data back
        for(int i=0; i<images.Count; i++)
        {
            TextureImporter importer = TextureImporter.GetAtPath(wd+images_data[i].str) as TextureImporter;
            //importer.assetPath = images_data[i].str;
            importer.mipmapEnabled = false;
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Multiple;
            importer.spritesheet = sprite_metadata[i].ToArray();

            try
            {
                AssetDatabase.StartAssetEditing();
                AssetDatabase.ImportAsset(importer.assetPath);
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
            }
        }

        //load sprite dictionary
        Dictionary<String,Sprite> sprites = new Dictionary<string, Sprite> ();
        for(int i=0; i<images_data.Count; i++)
        {
            Sprite[] sp = AssetDatabase.LoadAllAssetsAtPath( wd+images_data[i].str ).OfType<Sprite>().ToArray();
            for(int j=0; j<sp.Length; j++)
            {
                sprites[sp[j].name] = sp[j];
            }
        }

        //create animations
        int fps = (int)data.GetField ("framerate").f;
        List<string> animation_names = data.GetField ("animations").keys;

        foreach(string animationName in animation_names)
        {
            JSONObject animationJson = data.GetField("animations").GetField(animationName);
            List<JSONObject> frame_Data = animationJson.GetField("frames").list;
            float fpsinc = 1/(float)fps;

            EditorCurveBinding curveBinding = new EditorCurveBinding();
            curveBinding.type = typeof(SpriteRenderer);
            curveBinding.path = "";
            curveBinding.propertyName = "m_Sprite";

            List<ObjectReferenceKeyframe> keyframes = new List<ObjectReferenceKeyframe>();
            string lastFrame = "";
            for(int i=0; i<frame_Data.Count; i++)
            {
                string fname = frame_Data[i].f.ToString();
                if(i == frame_Data.Count-1 || fname!=lastFrame)
                {
                    ObjectReferenceKeyframe k = new ObjectReferenceKeyframe();
                    k.time = i*fpsinc;
                    k.value = sprites[prefix+"_"+fname];
                    keyframes.Add(k);
                    lastFrame = fname;
                }
            }

            AnimationClip clip = new AnimationClip();
            clip.frameRate = (float)fps;
            clip.legacy = false;
            clip.EnsureQuaternionContinuity();

            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyframes.ToArray());

            //load asset if it exists, else create new
            AnimationClip a = AssetDatabase.LoadAssetAtPath<AnimationClip>(wd + animationName + ".anim");
            if(a!= null)
            {
                Debug.Log("update clip");
                clip.wrapMode = a.wrapMode;
                a = clip;
            } else
            {
                AssetDatabase.CreateAsset(clip, wd + animationName + ".anim");
            }
        }
        AssetDatabase.SaveAssets();
    }
Exemplo n.º 28
0
        /// <summary>
        /// Creates an <see cref="AnimationClip"/> of a sprite animation using the given <see cref="Sprite"/> frames and frames per second.
        /// </summary>
        /// <param name="name">The name of the animation to create.</param>
        /// <param name="sprites">The list of <see cref="Sprite"/> objects making up the frames of the animation.</param>
        /// <param name="fps">The frames per second for the animation.</param>
        /// <returns>The newly constructed <see cref="AnimationClip"/></returns>
        private static AnimationClip CreateSpriteAnimationClip(string name, IList<Sprite> sprites, float fps)
        {
            float frameLength = 1f / fps;

            AnimationClip clip = new AnimationClip();
            clip.name = name;
            clip.frameRate = fps;
            clip.wrapMode = WrapMode.Loop;

            // The AnimationClipSettings cannot be set in Unity (as of 4.6) and must be editted via SerializedProperty
            // from: http://forum.unity3d.com/threads/can-mecanim-animation-clip-properties-be-edited-in-script.251772/
            SerializedObject serializedClip = new SerializedObject(clip);
            SerializedProperty serializedSettings = serializedClip.FindProperty("m_AnimationClipSettings");
            serializedSettings.FindPropertyRelative("m_LoopTime").boolValue = true;
            serializedClip.ApplyModifiedProperties();

            EditorCurveBinding curveBinding = new EditorCurveBinding();
            curveBinding.type = typeof(SpriteRenderer);
            curveBinding.propertyName = "m_Sprite";

            ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[sprites.Count];

            for (int i = 0; i < sprites.Count; i++)
            {
                ObjectReferenceKeyframe kf = new ObjectReferenceKeyframe();
                kf.time = i * frameLength;
                kf.value = sprites[i];
                keyFrames[i] = kf;
            }

            #if UNITY_5
            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);
            #else // Unity 4
            AnimationUtility.SetAnimationType(clip, ModelImporterAnimationType.Generic);
            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);

            clip.ValidateIfRetargetable(true);
            #endif

            AssetDatabase.CreateAsset(clip, GetRelativePath(currentPath) + "/" + name + ".anim");

            return clip;
        }
		public void CreateAnimation(string path, string masterName, AsepriteAnimation anim, List<Sprite> sprites)
		{
			AnimationClip clip;
            string fileName = path + "/" + masterName + "_" + anim.name + ".anim";

			// check if animation file already exists
			clip = AssetDatabase.LoadAssetAtPath<AnimationClip>(fileName);
			if (clip == null)
			{
				clip = new AnimationClip();
				AssetDatabase.CreateAsset(clip, fileName);
			}

			// change loop settings
			if (ShouldLoop(anim.name))
			{
				clip.wrapMode = WrapMode.Loop;
				clip.SetLoop(true);
			}
			else
			{
				clip.wrapMode = WrapMode.Clamp;
				clip.SetLoop(false);
			}

			EditorCurveBinding curveBinding = new EditorCurveBinding
			{
				type = typeof(SpriteRenderer),
				propertyName = "m_Sprite"
			};

			ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[anim.Count + 1]; // one more than sprites because we repeat the last sprite
			float timePoint;

			for (int i = 0; i < anim.Count; i++)
			{
				timePoint = anim.GetTimePoint(i);
				ObjectReferenceKeyframe keyFrame = new ObjectReferenceKeyframe { time = timePoint };

				Sprite sprite = sprites[i + anim.from];
				keyFrame.value = sprite;
				keyFrames[i] = keyFrame;
			}

			// repeating the last frame at a point "just before the end" so the animation gets its correct length

			timePoint = anim.GetTimePoint(anim.Count);
			ObjectReferenceKeyframe lastKeyFrame = new ObjectReferenceKeyframe { time = timePoint - (1f / clip.frameRate) };
			Sprite lastSprite = sprites[anim.Count - 1 + anim.from];
			lastKeyFrame.value = lastSprite;
			keyFrames[anim.Count] = lastKeyFrame;

			// save animation clip values
			AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);
			EditorUtility.SetDirty(clip);
			anim.animationClip = clip;
		}
Exemplo n.º 30
0
 private void CreateNewPPtrKeyframe(float time, UnityEngine.Object value, AnimationWindowCurve targetCurve)
 {
     ObjectReferenceKeyframe key = new ObjectReferenceKeyframe {
         time = time,
         value = value
     };
     AnimationWindowKeyframe keyframe2 = new AnimationWindowKeyframe(targetCurve, key);
     AnimationKeyTime keyTime = AnimationKeyTime.Time(keyframe2.time, this.state.frameRate);
     targetCurve.AddKeyframe(keyframe2, keyTime);
     this.state.SelectKey(keyframe2);
 }
	public void OnGUI()
	{
		if (animationClips.Count > 0 ) {
			scrollPos = GUILayout.BeginScrollView(scrollPos, GUIStyle.none);

			EditorGUILayout.BeginHorizontal();
			GUILayout.Label("Animation Clip:", GUILayout.Width(columnWidth));

			if ( animationClips.Count == 1 )
			{
				animationClips[0] = ((AnimationClip)EditorGUILayout.ObjectField(
					animationClips[0],
					typeof(AnimationClip),
					true,
					GUILayout.Width(columnWidth))
					);
			} 
			else
			{
				GUILayout.Label("Multiple Anim Clips: " + animationClips.Count, GUILayout.Width(columnWidth));
			}
			EditorGUILayout.EndHorizontal();

			GUILayout.Space(20);

			EditorGUILayout.BeginHorizontal();
			
			EditorGUILayout.LabelField ("Sprites:");

			EditorGUILayout.EndHorizontal();
			
			EditorGUILayout.BeginHorizontal();
			
			GUILayout.Label("Original Sprite Text:", GUILayout.Width(columnWidth));
			GUILayout.Label("Replacement Sprite Text:", GUILayout.Width(columnWidth));

			EditorGUILayout.EndHorizontal();

			EditorGUILayout.BeginHorizontal();
			originalSpriteText = EditorGUILayout.TextField(originalSpriteText, GUILayout.Width(columnWidth));
			replaceSpriteText = EditorGUILayout.TextField(replaceSpriteText, GUILayout.Width(columnWidth));
			if (GUILayout.Button("Replace All Sprites")) {
				changeAllSprites = true;
			}

			EditorGUILayout.EndHorizontal();

			foreach (AnimationClip clip in animationClips) {
				// First you need to create e Editor Curve Binding
				EditorCurveBinding curveBinding = new EditorCurveBinding();
				 
				// I want to change the sprites of the sprite renderer, so I put the typeof(SpriteRenderer) as the binding type.
				curveBinding.type = typeof(SpriteRenderer);
				// Regular path to the gameobject that will be changed (empty string means root)
				curveBinding.path = "";
				// This is the property name to change the sprite of a sprite renderer
				curveBinding.propertyName = "m_Sprite";
				 
				// An array to hold the object keyframes
				ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[10];
	 
				foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings (clip))
				{
					if (binding.propertyName == "m_Sprite") {
						ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve (clip, binding);
						EditorGUILayout.LabelField (binding.path + "/" + binding.propertyName + ", Keys: " + keyframes.Length);
						for (int i = 0; i < keyframes.Length; i++) {
							if (changeAllSprites) {
								Sprite keyframeSprite = (Sprite)keyframes[i].value;
								if (keyframeSprite != null) {
									string spriteName = keyframeSprite.name;
									string newSpriteName = spriteName.Replace(originalSpriteText, replaceSpriteText);
									Debug.Log(newSpriteName);
									GetAllSprites();
									if (sprites.Length > 0) {
										bool foundSprite = false;
										foreach (Sprite sprite in sprites) {
											if (sprite != null && sprite.name == newSpriteName) {
												float timeForKey = keyframes[i].time;
												keyframes[i] = new ObjectReferenceKeyframe();
												// set the time
												keyframes[i].time = timeForKey;
												// set reference for the sprite you want
												keyframes[i].value = sprite;
												AnimationUtility.SetObjectReferenceCurve(clip, binding, keyframes);
												Debug.Log("Sprite changed to " + sprite.name);
												break;
											}
										}
									}
								}
							}
							EditorGUILayout.ObjectField (keyframes[i].value, typeof (Sprite), false);
						}
					}
				}
			}
			changeAllSprites = false;
			GUILayout.Space(40);
			GUILayout.EndScrollView();
		} else {
			GUILayout.Label("Please select an Animation Clip");
		}
	}
Exemplo n.º 32
0
 public AnimationWindowKeyframe(AnimationWindowCurve curve, ObjectReferenceKeyframe key)
 {
     this.time = key.time;
     this.value = key.value;
     this.curve = curve;
 }
Exemplo n.º 33
0
            private ObjectReferenceKeyframe[] CreateKeysForKeyframeRanges(Sprite[] sprites, KeyframeRange[] keyframeRanges, int samplesPerSecond)
            {
                List<ObjectReferenceKeyframe> keys = new List<ObjectReferenceKeyframe>();
                float timePerFrame = 1.0f / samplesPerSecond;
                int currentKeyIndex = 0;
                float currentTime = 0.0f;
                for (int rangeIndex = 0; rangeIndex < this.animationKeyframes.Length; rangeIndex++)
                {
                    KeyframeRange range = this.animationKeyframes[rangeIndex];

                    // Skip invalid ranges
                    if (!range.IsValid() || sprites == null)
                    {
                        Debug.LogWarning("Found invalid KeyframeRange. Skipping Range on Clip: " + this.clipName);
                        continue;
                    }

                    float timePerSubkey = range.SamplesPerFrame * timePerFrame;
                    for (int subkey = 0; subkey < range.NumKeyframes; subkey++)
                    {
                        int spriteIndex = range.FirstFrame + subkey;
                        if (spriteIndex >= sprites.Length)
                        {
                            Debug.LogError("Sprite not found at index: " + spriteIndex +
                                " for clip: " + this.clipName + ". RangeIndex: " + rangeIndex);
                            return null;
                        }

                        ObjectReferenceKeyframe keyframe = new ObjectReferenceKeyframe();
                        keyframe.time = currentTime;
                        keyframe.value = sprites[spriteIndex];
                        keys.Add(keyframe);

                        currentTime += timePerSubkey;
                        currentKeyIndex++;
                    }
                }

                // If the last KeyframeRange is longer than one frame we need to add a keyframe at the end of the interval
                // to keep anim from ending early
                if (keyframeRanges.Last().IsValid() && keyframeRanges.Last().SamplesPerFrame > 1)
                {
                    ObjectReferenceKeyframe keyframe = new ObjectReferenceKeyframe();
                    keyframe.time = currentTime - timePerFrame;
                    keyframe.value = sprites[keyframeRanges.Last().LastFrame];
                    keys.Add(keyframe);
                }

                return keys.ToArray();
            }