Unity-WIKI 之 AnimationToPNG
组件功能
把3D角色的动画录制成PNG一帧一帧输出,这是一个件多么美好的事!
可能遇到问题
有可能当你新建完脚本时会出现下面的错误:
`System.IO.File' does not contain a definition for `WriteAllBytes'
解决办法:切换当前的Platform为其它平台(WINDOWS)
3D模型和导出的png


使用方法
新建一个空的GameObject,附加上此脚本,配置好参数,按Play,会自动完成,可以到Project Path/Folder 目录下找到输出的文件
AnimationToPNG源码
CSharp - AnimationToPNG.cs
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO; /*
The MIT License (MIT) Copyright (c) 2014 Brad Nelson and Play-Em Inc. Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/ // AnimationToPNG is based on Twinfox and bitbutter's Render Particle to Animated Texture Scripts,
// this script will render out an animation that is played when "Play" is pressed in the editor. /*
Basically this is a script you can attach to any gameobject in the scene. If you have Unity Pro, you can use Render Textures, which can accurately
render the transparent background for your animations easily in full resolution
of the camera. The script will autodetect if you have Unity Pro and use
Render Textures automatically. If you are using Unity Free, then the screen will have a split area using
half of the screen width to render the animations. You can change the "animationName" to a string of your choice for a
prefix for the output file names, if it is left empty then no filename
will be added. The destination folder is relative to the Project Folder root, so you
can change the string to a folder name of your choice and it will be
created. If it already exists, it will simply create a new folder with a
number incremented as to how many of those named folders exist. Choose how many frames per second the animation will run by changing the
"frameRate" variable, and how many frames of the animation you wish to
capture by changing the "framesToCapture" variable. Once "Play" is pressed in the Unity Editor, it should output all the
animation frames to PNGs output in the folder you have chosen, and will
stop capturing after the number of frames you wish to capture is
completed.
*/ public class AnimationToPNG : MonoBehaviour
{ // Animation Name to be the prefix for the output filenames
public string animationName = ""; // Default folder name where you want the animations to be output
public string folder = "PNG_Animations"; // Framerate at which you want to play the animation
public int frameRate = 25; // How many frames you want to capture during the animation
public int framesToCapture = 25; // White Camera
private Camera whiteCam; // Black Camera
private Camera blackCam; // Pixels to World Unit size
public float pixelsToWorldUnit = 74.48275862068966f; // If you have Unity Pro you can use a RenderTexture which will render the full camera width, otherwise it will only render half
private bool useRenderTexture = false; private int videoframe = 0; // how many frames we've rendered private float originaltimescaleTime; // track the original time scale so we can freeze the animation between frames private string realFolder = ""; // real folder where the output files will be private bool done = false; // is the capturing finished? private bool readyToCapture = false; // Make sure all the camera setup is complete before capturing private float cameraSize; // Size of the orthographic camera established from the current screen resolution and the pixels to world unit private Texture2D texb; // black camera texture private Texture2D texw; // white camera texture private Texture2D outputtex; // final output texture private RenderTexture blackCamRenderTexture; // black camera render texure private RenderTexture whiteCamRenderTexture; // white camera render texure public void Start()
{
useRenderTexture = Application.HasProLicense(); // Set the playback framerate!
// (real time doesn't influence time anymore)
Time.captureFramerate = frameRate; // Create a folder that doesn't exist yet. Append number if necessary.
realFolder = folder;
int count = 1;
while (Directory.Exists(realFolder))
{
realFolder = folder + count;
count++;
}
// Create the folder
Directory.CreateDirectory(realFolder); originaltimescaleTime = Time.timeScale; // Force orthographic camera to render out sprites per pixel size designated by pixels to world unit
cameraSize = Screen.width / (((Screen.width / Screen.height) * 2) * pixelsToWorldUnit); GameObject bc = new GameObject("Black Camera");
bc.transform.localPosition = new Vector3(0, 0, -1);
blackCam = bc.AddComponent<Camera>();
blackCam.backgroundColor = Color.black;
blackCam.orthographic = true;
blackCam.orthographicSize = cameraSize;
blackCam.tag = "MainCamera"; GameObject wc = new GameObject("White Camera");
wc.transform.localPosition = new Vector3(0, 0, -1);
whiteCam = wc.AddComponent<Camera>();
whiteCam.backgroundColor = Color.white;
whiteCam.orthographic = true;
whiteCam.orthographicSize = cameraSize; // If not using a Render Texture then set the cameras to split the screen to ensure we have an accurate image with alpha
if (!useRenderTexture)
{
// Change the camera rects to have split on screen to capture the animation properly
blackCam.rect = new Rect(0.0f, 0.0f, 0.5f, 1.0f); whiteCam.rect = new Rect(0.5f, 0.0f, 0.5f, 1.0f);
}
// Cameras are set ready to capture!
readyToCapture = true;
} void Update()
{
// If the capturing is not done and the cameras are set, then Capture the animation
if (!done && readyToCapture)
{
StartCoroutine(Capture());
}
} void LateUpdate()
{
// When we are all done capturing, clean up all the textures and RenderTextures from the scene
if (done)
{
DestroyImmediate(texb);
DestroyImmediate(texw);
DestroyImmediate(outputtex); if (useRenderTexture)
{
//Clean Up
whiteCam.targetTexture = null;
RenderTexture.active = null;
DestroyImmediate(whiteCamRenderTexture); blackCam.targetTexture = null;
RenderTexture.active = null;
DestroyImmediate(blackCamRenderTexture);
}
}
} IEnumerator Capture()
{
if (videoframe < framesToCapture)
{
// name is "realFolder/animationName0000.png"
// string name = realFolder + "/" + animationName + Time.frameCount.ToString("0000") + ".png";
string filename = String.Format("{0}/" + animationName + "{1:D04}.png", realFolder, Time.frameCount); // Stop time
Time.timeScale = 0;
// Yield to next frame and then start the rendering
yield return new WaitForEndOfFrame(); // If we are using a render texture to make the animation frames then set up the camera render textures
if (useRenderTexture)
{
//Initialize and render textures
blackCamRenderTexture = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32);
whiteCamRenderTexture = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32); blackCam.targetTexture = blackCamRenderTexture;
blackCam.Render();
RenderTexture.active = blackCamRenderTexture;
texb = GetTex2D(true); //Now do it for Alpha Camera
whiteCam.targetTexture = whiteCamRenderTexture;
whiteCam.Render();
RenderTexture.active = whiteCamRenderTexture;
texw = GetTex2D(true);
}
// If not using render textures then simply get the images from both cameras
else
{
// store 'black background' image
texb = GetTex2D(true); // store 'white background' image
texw = GetTex2D(false);
} // If we have both textures then create final output texture
if (texw && texb)
{ int width = Screen.width;
int height = Screen.height; // If we are not using a render texture then the width will only be half the screen
if (!useRenderTexture)
{
width = width / 2;
}
outputtex = new Texture2D(width, height, TextureFormat.ARGB32, false); // Create Alpha from the difference between black and white camera renders
for (int y = 0; y < outputtex.height; ++y)
{ // each row
for (int x = 0; x < outputtex.width; ++x)
{ // each column
float alpha;
if (useRenderTexture)
{
alpha = texw.GetPixel(x, y).r - texb.GetPixel(x, y).r;
}
else
{
alpha = texb.GetPixel(x + width, y).r - texb.GetPixel(x, y).r;
}
alpha = 1.0f - alpha;
Color color;
if (alpha == 0)
{
color = Color.clear;
}
else
{
color = texb.GetPixel(x, y) / alpha;
}
color.a = alpha;
outputtex.SetPixel(x, y, color);
}
} // Encode the resulting output texture to a byte array then write to the file
byte[] pngShot = outputtex.EncodeToPNG();
File.WriteAllBytes(filename, pngShot);
print(filename+" "); // Reset the time scale, then move on to the next frame.
Time.timeScale = originaltimescaleTime;
videoframe++;
} // Debug.Log("Frame " + name + " " + videoframe);
}
else
{
Debug.Log("Complete! " + videoframe + " videoframes rendered (0 indexed)");
done = true;
}
} // Get the texture from the screen, render all or only half of the camera
private Texture2D GetTex2D(bool renderAll)
{
// Create a texture the size of the screen, RGB24 format
int width = Screen.width;
int height = Screen.height;
if (!renderAll)
{
width = width / 2;
} Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
return tex;
}
}
WIKI资料
http://wiki.unity3d.com/index.php/AnimationToPNG
Unity-WIKI 之 AnimationToPNG的更多相关文章
- 基于Unity有限状态机框架
这个框架是Unity wiki上的框架.网址:http://wiki.unity3d.com/index.php/Finite_State_Machine 这就相当于是“模板”吧,自己写的代码,写啥都 ...
- Unity 相关经典博客资源总结(持续更新)
就作为一个记录吧,把平时看过的Unity相关的一些好的Blog记录并分享. 好的论坛: Unity官方脚本 点评:这个不用说了,最核心的内容,理解整个Unity引擎的方方面面,梳理结构. Unity ...
- 【Unity3D基础教程】给初学者看的Unity教程(零):如何学习Unity3D
作者:王选易,出处:http://www.cnblogs.com/neverdie/ 欢迎转载,也请保留这段声明.如果你喜欢这篇文章,请点推荐.谢谢! Unity3D有什么优势 Unity3D是一个跨 ...
- 【转】Unity 相关经典博客资源总结(持续更新)
原文:http://blog.csdn.net/prothi/article/details/20123319 就作为一个记录吧,把平时看过的Unity相关的一些好的Blog记录并分享. 好的论坛: ...
- 【Unity Shader】2D动态云彩
写在前面 赶在年前写一篇文章.之前翻看2015年的SIGGRAPH Course(关于渲染的可以去selfshadow的博客里找到,很全)的时候看到了关于体积云的渲染.这个课程讲述了开发者为游戏< ...
- Unity Shaderlab: Object Outlines 转
转 https://willweissman.wordpress.com/tutorials/shaders/unity-shaderlab-object-outlines/ Unity Shader ...
- 学习Unity的步骤
作者:王选易链接:https://www.zhihu.com/question/23790314/answer/46815232来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...
- Unity FSM 有限状态机
翻译了一下unity wiki上对于有限状态机的案例,等有空时在详细写一下.在场景中添加两个游戏物体,一个为玩家并修改其Tag为Player,另一个为NPC为其添加NPCControl脚本,并为其将玩 ...
- unity 3d开发的大型网络游戏
unity 3d开发的大型网络游戏 一.总结 1.unity的官网上面应该有游戏列表 2.unity3D是很好的3d游戏引擎,也支持2d,也能做很多画面精良的3A级游戏 3.范围:电脑游戏,手机游戏, ...
- 2019年Unity学习资源指南[精心整理]
前言 进入一个领域,最直接有效的方法就是,寻找相关综述性文章,首先你需要对你入门的领域有个概括性的了解,这些包括: 1.主流的学习社区与网站. 2.该领域的知名大牛与热心分享的从业者. 3.如何有效的 ...
随机推荐
- 如何选择RabbitMQ的消息保存方式?
RabbitMQ对于queue中的message的保存方式有两种方式:disc和ram.如果采用disc,则需要对exchange/queue/delivery mode都要设置成durable模式. ...
- spring mvc绑定复杂对象报错“Could not instantiate property type [com.ld.net.spider.pojo.WorkNode] to auto-grow nested property path: java.lang.InstantiationException: com.ld.net.spider.pojo.WorkNode”
解决方法之一: 1.确保所有的Pojo都包含了默认的构造器:
- Win10安装framework3.5
.NET少不了framewrok,其版本也比较多,默认情况下win7及上版本没有安装framework3.5,但有些软件又需要它,比如arcgis软件在安装时会检测是否存在3.5,如果没有,将不会正常 ...
- C++指针笔记
什么是指针: 指针是一个特殊的变量,它里面存储的数值被解释成为内存里的一个地址.通过指针我们可以直接对内存进行操作. 什么是地址: 比如你要给你朋友寄快递,在寄东西的时候是不是要填写地址,通过地址你的 ...
- SharePoint 2013 对象模型操作"网站设置"菜单
在SharePoint的开发中,经常会有客户提到网站操作上的栏目过多,其实,我们除了可以通过Feature的方式添加,还可以通过服务器端对象模型的方式添加:下面,让我用简单的例子,给大家介绍一下: 1 ...
- 利用在线工具根据JSon数据自动生成对应的Java实体类
如果你希望根据JSon数据自动生成对应的Java实体类,并且希望能进行变量的重命名,那么“JSON To Java”一定适合你.(下面的地址需要FQ) https://jsontojava.appsp ...
- 安卓开发_浅谈SubMenu(子菜单)
子菜单,即点击菜单后出现一个菜单栏供选择 创建子菜单的步骤: (1) 覆盖Activity的onCreateOptionsMenu()方法,调用Menu的addSubMenu()方法来添加子菜单 (2 ...
- iOS之 开发中用得到的开源github
github:无限图片轮播 https://github.com/dymx101/DYMRollingBanner 2.灌水动画 https://github.com/dsxNiubility/SXW ...
- ReSharper 卸载后 VS2012 没有提示问题
虽然ReSharper非常强大,但由于公司电脑配置太差,被迫卸载了.但发现卸载后,VS2012自带的提示都没有了. 网上找了下相关的解决方法.摘抄下来,作为自己笔记. 解决方法原文出处:http:// ...
- 双系统如何删除Linux,恢复Windows从MBR引导启动?
嗯,现在愿意尝试Linux的人越来越多了.通常,如果一台电脑里已经装有了Windows,再装Linux,安装时,Linux的grub引导程 序就会覆盖掉保存在MBR当中的原来的Windows引导程序. ...