Net.Like.Xue.Tokyo/Packages-Local/Net.BITKit.Bounds.Unity/DrawMinimapToPng.cs

107 lines
3.4 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Net.Project.B.Bounds
{
public class DrawMinimapToPng
{
[MenuItem("Tools/Draw Minimap To Png")]
private static void ExportConvex()
{
var renderLayer = LayerMask.NameToLayer("Ignore Raycast");
var go = Selection.activeGameObject;
if (!go)
{
Debug.LogError("No object selected");
return;
}
Debug.Log($"正在从:{go.name}创建minimap");
var bounds = new UnityEngine.Bounds();
var renderGroup = new GameObject();
var children = go.GetComponentsInChildren<MeshRenderer>(true);
for (var index = 0; index < children.Length; index++)
{
var renderer = children[index];
if (index is 0)
{
bounds = renderer.bounds;
}
else
{
bounds.Encapsulate(renderer.bounds);
}
var instance = Object.Instantiate(renderer.gameObject, renderGroup.transform, true);
instance.layer = renderLayer;
foreach (var transform in instance.GetComponentsInChildren<Transform>())
{
transform.gameObject.layer = renderLayer;
}
}
var camera = new GameObject("MinimapCamera").AddComponent<Camera>();
var position = bounds.center+Vector3.up*bounds.size.y;
position.y = Mathf.Clamp(position.y,64,position.y);
camera.transform.position = position;
camera.transform.LookAt(bounds.center);
camera.orthographic = true;
camera.orthographicSize = Mathf.Max(bounds.size.x,bounds.size.y)/2;
camera.clearFlags = CameraClearFlags.SolidColor;
camera.backgroundColor = Color.clear;
camera.cullingMask = LayerMask.GetMask("Ignore Raycast");
var rendererTexture = new RenderTexture(1024,1024,32);
camera.targetTexture = rendererTexture;
camera.Render();
var texture = new Texture2D(rendererTexture.width, rendererTexture.height, TextureFormat.RGBA32, false);
RenderTexture.active = rendererTexture;
texture.ReadPixels(new Rect(0, 0, rendererTexture.width, rendererTexture.height), 0, 0);
texture.Apply();
RenderTexture.active = null;
//camera.targetTexture = null;
//Object.DestroyImmediate(rendererTexture);
var path = EditorUtility.SaveFilePanel(
"Save Minimap To Png",
"",
"Minimap.png",
"png");
if (string.IsNullOrEmpty(path) is false)
{
var png = texture.EncodeToPNG();
System.IO.File.WriteAllBytes(path,png);
}
camera.targetTexture = null;
Object.DestroyImmediate(renderGroup);
Object.DestroyImmediate(rendererTexture);
Object.DestroyImmediate(texture);
Object.DestroyImmediate(camera.gameObject);
Debug.Log(bounds);
}
}
}