LoginSignup
13
16

More than 5 years have passed since last update.

カメラが映すものを低解像度に設定する

Posted at

レンダーテクスチャーを設定して表示物の解像度を落とす機能。
処理負荷軽減に使ったり、むやみに解像度が高い端末の負荷が上がるのを制御したりするために使う。(iPadやAndroid)
カメラにコンポーネントを設定するだけでOK。

http://wordpress.notargs.com/blog/blog/2016/10/03/unityたった1個のスクリプトだけで画面解像度を下げ/
※これをカスタムしました

▼こんな感じ
8b9a1da1-e58e-63c6-76b3-4b73fd7e2c12.gif

LowResolutionCamera.cs
using UnityEngine;
using UnityEngine.Rendering;

/// <summary>
/// カメラが映すものを低解像度に設定できるようにするコンポーネント
/// </summary>
[RequireComponent(typeof(Camera))]
public class LowResolutionCamera : MonoBehaviour {
    /// <summary>
    /// デフォルト解像度
    /// </summary>
    private readonly Vector2 RESOLUTION = new Vector2(750, 1334);

    /// <summary>
    /// 解像度係数
    /// </summary>
    [SerializeField, Range(0.1f, 1)]
    private float _resolutionWeight = 1f;

    private float _currentResolutionWeight = 1f;

    private RenderTexture _renderTexture;
    private Camera _camera;
    private Camera _subCamera;

    private void Start() {
        SetResolution(_resolutionWeight);
    }

    /// <summary>
    /// 解像度を設定
    /// </summary>
    public void SetResolution(float resolutionWeight) {
        _resolutionWeight = resolutionWeight;
        _currentResolutionWeight = resolutionWeight;

        // 指定解像度に合わせたレンダーテクスチャーを作成
        _renderTexture = new RenderTexture(
            width: (int)(RESOLUTION.x * _currentResolutionWeight),
            height: (int)(RESOLUTION.y * _currentResolutionWeight),
            depth: 24
        );
        _renderTexture.useMipMap = false;
        _renderTexture.filterMode = FilterMode.Point;
        // カメラのレンダーテクスチャーを設定
        if (_camera == null) {
            _camera = GetComponent<Camera>();
        }
        _camera.targetTexture = _renderTexture;

        // レンダーテクスチャーを表示するサブカメラを設定
        if (_subCamera == null) {
            GameObject cameraObject = new GameObject("SubCamera");
            _subCamera = cameraObject.AddComponent<Camera>();
            _subCamera.cullingMask = 0;
            _subCamera.transform.parent = transform;
        }
        CommandBuffer commandBuffer = new CommandBuffer();
        commandBuffer.Blit((RenderTargetIdentifier)_renderTexture, BuiltinRenderTextureType.CameraTarget);
        _subCamera.AddCommandBuffer(CameraEvent.AfterEverything, commandBuffer);
    }

    private void Update() {
        if (_currentResolutionWeight == _resolutionWeight) return;
        // _resolutionWeightの値が更新された時だけ解像度変更処理を呼ぶ
        // Inspector上で_resolutionWeightを操作するとき用の処理
        SetResolution(_resolutionWeight);
    }
}

・Inspector上で調整できるようにしているが、リリース時には無駄なのでifdefで囲んだり、消したりを推奨
・クラス内で定義しているRESOLUTIONも、ゲーム内のいろんなところで使うので、共通の定数用のクラスに外だししたほうが良い
・Auto Orientation(端末を傾けて画面向き変更)を対応させるときもRenderTextureの解像度変更しないといけない

13
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16