Skip to content

Instantly share code, notes, and snippets.

@FroggerHH
Created June 7, 2024 11:54
Show Gist options
  • Select an option

  • Save FroggerHH/599609d99537357ee4260e35f97622dd to your computer and use it in GitHub Desktop.

Select an option

Save FroggerHH/599609d99537357ee4260e35f97622dd to your computer and use it in GitHub Desktop.
Capture and save large mode of minimap as png file to the game root folder. Spend big time messing with this code. Hope it will save someone's time.
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using BepInEx;
using JetBrains.Annotations;
using UnityEngine;
using static UnityEngine.Object;
[PublicAPI]
public static class MapCapture
{
[Description("Capture and save large mode of minimap as png file to the game root folder.")]
public static async Task CaptureAndSaveMap()
{
var mode = Minimap.instance.m_mode;
Minimap.instance.SetMapMode(Minimap.MapMode.Large);
await Task.Yield();
Minimap.instance.SetMapMode(mode);
var material = Minimap.instance.m_mapLargeShader;
var savePath = Path.Combine(Paths.GameRootPath, "map.png");
var width = material.mainTexture.width;
var height = material.mainTexture.height;
var renderTexture = new RenderTexture(width, height, 24);
renderTexture.name = "Temp_MapRenderTexture";
renderTexture.enableRandomWrite = true;
renderTexture.Create();
var tempQuad = GameObject.CreatePrimitive(PrimitiveType.Quad);
tempQuad.GetComponent<MeshRenderer>().material = material;
var tempCameraObject = new GameObject("Temp_MapCamera");
var tempCamera = tempCameraObject.AddComponent<Camera>();
tempCamera.targetTexture = renderTexture;
tempCamera.orthographic = true;
tempCamera.orthographicSize = 0.5f;
tempCamera.nearClipPlane = -1f;
tempCamera.farClipPlane = 1f;
tempCamera.clearFlags = CameraClearFlags.Color;
tempCamera.backgroundColor = Color.clear;
tempQuad.transform.position = tempCamera.transform.position + tempCamera.transform.forward;
tempQuad.transform.localScale = new Vector3(1, 1, 1);
RenderTexture.active = renderTexture;
tempCamera.Render();
var texture = new Texture2D(width, height, TextureFormat.RGB24, false);
texture.name = "Temp_MapTexture";
texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
texture.Apply();
var bytes = texture.EncodeToPNG();
File.WriteAllBytes(savePath, bytes);
RenderTexture.active = null;
DestroyImmediate(tempCameraObject);
DestroyImmediate(tempQuad);
renderTexture.Release();
DestroyImmediate(renderTexture);
DestroyImmediate(texture);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment