using UnityEngine; using UnityEngine.UI; public class SetRenderTextureSize : MonoBehaviour { [SerializeField] [Range(100, 1200)] private int resolutionWidth; private int oldResolutionWidth; private int oldScreenWidth; private int oldScreenHeight; [SerializeField] private RawImage renderImage; // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { RecalculateTexture(); } void Update() { if (resolutionWidth != oldResolutionWidth || Screen.width != oldScreenWidth || Screen.height != oldScreenHeight) { RecalculateTexture(); } } private void RecalculateTexture() { Camera camera = gameObject.GetComponent(); if (camera.targetTexture != null) { camera.targetTexture.Release(); } float aspectRatio = (float)Screen.width / Screen.height; int resolutionHeight = Mathf.RoundToInt(resolutionWidth / aspectRatio); if (resolutionHeight < 1) { resolutionHeight = 1; } camera.targetTexture = new RenderTexture( resolutionWidth, resolutionHeight, 24 ); camera.targetTexture.filterMode = FilterMode.Point; camera.targetTexture.wrapMode = TextureWrapMode.Clamp; renderImage.texture = camera.targetTexture; renderImage.color = new Color(renderImage.color.r, renderImage.color.g, renderImage.color.b, 255); oldResolutionWidth = resolutionWidth; oldScreenWidth = Screen.width; oldScreenHeight = Screen.height; } }