うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Editor でキャラ等 の画像を撮影できるツールのサンプル ~コード解説~

https://hacchi-man.hatenablog.com/entry/2020/05/04/220000hacchi-man.hatenablog.com

キャプチャ機能で使った一部処理を抜粋

RenderTexture を GUI に表示

// カメラの描画を更新
_camera.Render();
var rect = GUILayoutUtility.GetRect(_renderTexture.width, _renderTexture.height, GUILayout.MaxWidth(_renderTexture.width), GUILayout.MaxHeight(_renderTexture.height));
EditorGUI.DrawTextureTransparent(rect, _renderTexture);

RenderTexture を png として保存

RenderTexture.active = _renderTexture;
var texture = new Texture2D(_renderTexture.width, _renderTexture.height, TextureFormat.ARGB32, false);
texture.ReadPixels(new Rect(0, 0, _renderTexture.width, _renderTexture.height), 0, 0, false);
texture.Apply();

// png として保存
System.IO.File.WriteAllBytes(savePath, texture.EncodeToPNG());

Object.DestroyImmediate(texture);

Animation の指定フレームを表示

_animator.speed = 0f;
_animator.Play(name, 0, normalizedTime);
_animator.Update(Time.deltaTime);

Animation Clip 一覧を表示

var clips = _animator.runtimeAnimatorController.animationClips.Select(ac => ac.name).ToArray();
if (_animationIndex >= clips.Length)
    _animationIndex = 0;
 
using (var check = new EditorGUI.ChangeCheckScope())
{
    _animationIndex = EditorGUILayout.Popup("Animation", _animationIndex, clips);
    if (check.changed)
        _maxLength = _animator.runtimeAnimatorController.animationClips[_animationIndex].length;
}