Open2

[Unity] Cameraスクリプト

gonCgonC

Unityカメラで特定のレイヤーオブジェクトの表示・非表示を切り替える

CameraExtensions
using UnityEngine;


public static class CameraExtensions
{

    public static void LayerCullingShow(this Camera cam, int layerMask)
    {
        cam.cullingMask |= layerMask;
    }

    public static void LayerCullingShow(this Camera cam, string layer)
    {
        LayerCullingShow(cam, 1 << LayerMask.NameToLayer(layer));
    }

    public static void LayerCullingHide(this Camera cam, int layerMask)
    {
        cam.cullingMask &= ~layerMask;
    }

    public static void LayerCullingHide(this Camera cam, string layer)
    {
        LayerCullingHide(cam, 1 << LayerMask.NameToLayer(layer));
    }

    public static void LayerCullingToggle(this Camera cam, int layerMask)
    {
        cam.cullingMask ^= layerMask;
    }

    public static void LayerCullingToggle(this Camera cam, string layer)
    {
        LayerCullingToggle(cam, 1 << LayerMask.NameToLayer(layer));
    }

    public static bool LayerCullingIncludes(this Camera cam, int layerMask)
    {
        return (cam.cullingMask & layerMask) > 0;
    }

    public static bool LayerCullingIncludes(this Camera cam, string layer)
    {
        return LayerCullingIncludes(cam, 1 << LayerMask.NameToLayer(layer));
    }

    public static void LayerCullingToggle(this Camera cam, int layerMask, bool isOn)
    {
        bool included = LayerCullingIncludes(cam, layerMask);
        if (isOn && !included)
        {
            LayerCullingShow(cam, layerMask);
        }
        else if (!isOn && included)
        {
            LayerCullingHide(cam, layerMask);
        }
    }

    public static void LayerCullingToggle(this Camera cam, string layer, bool isOn)
    {
        LayerCullingToggle(cam, 1 << LayerMask.NameToLayer(layer), isOn);
    }
}
gonCgonC

ゲーム画面のスクリーンショット

画面のスクリーンショットを任意のRawImageに貼る

ScreenShot
public class Screenshot : MonoBehaviour
{
    public RawImage targetTexture; // キャプチャ結果を格納するテクスチャ
    Texture2D capturedTexture;

    public void ScreenCapture()
    {
        // カメラのレンダリングテクスチャをキャプチャする
        capturedTexture = new Texture2D(Screen.width, Screen.height);
        StartCoroutine(UpdateCurrentScreenShot());
    }

    private IEnumerator UpdateCurrentScreenShot()
    {
        // これがないとReadPixels()でエラーになる
        yield return new WaitForEndOfFrame();
        capturedTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        capturedTexture.Apply();
        targetTexture.texture = capturedTexture;
        ConvertBase64FromTexture();
    }

    private void ConvertBase64FromTexture()
    {
        //Texture->byte変換
        byte[] byte_Before = capturedTexture.EncodeToJPG();
        //BASE64への変換
        string encodedText
            = System.Convert.ToBase64String(byte_Before);
        Debug.Log(encodedText);
    }
}