I want to render an image from the camera. I followed this tutorial, https://www.youtube.com/watch?v=d-56p770t0U
Everything in the tutorial works fine.
I am now trying to use the Texture2D that was generated from the camera render as the base image for a material. When I do this the materials base texture is just an all white image instead of the camera render.
This is my code.
Line 66 of the second script is where I set the snapshot Texture2D as the cubeTests materials mainTexture.
The debug line on 65 prints the format of the Texture2D as expected. Which is RGB24.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//
public class PlayerScamInput : MonoBehaviour
{
[SerializeField] public SnapshotCamera snapCam;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
snapCam.CallTakeSnapshot();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
//https://www.youtube.com/watch?v=d-56p770t0U
public class SnapshotCamera : MonoBehaviour
{
[SerializeField] Camera snapCam;
[SerializeField] int resWidth = 256;
[SerializeField] int resHeight = 256;
[SerializeField] GameObject cubeTest;
Renderer cubeRenderer;
void Awake()
{
cubeRenderer = cubeTest.GetComponent<Renderer>();
if (snapCam.targetTexture == null)
{
snapCam.targetTexture = new RenderTexture(resWidth, resHeight, 24);
}
else
{
resWidth = snapCam.targetTexture.width;
resHeight = snapCam.targetTexture.height;
}
snapCam.gameObject.SetActive(false);
}
public void CallTakeSnapshot()
{
snapCam.gameObject.SetActive(true);
}
void LateUpdate()
{
if (snapCam.gameObject.activeInHierarchy)
{
Texture2D snapshot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, true); //Use true for in game world
snapCam.Render();
RenderTexture.active = snapCam.targetTexture;
snapshot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
byte[] bytes = snapshot.EncodeToPNG();
string fileName = SnapshotName();
System.IO.File.WriteAllBytes(fileName, bytes);
Debug.Log("snapshot taken");
AssetDatabase.Refresh();
//Set material texture
Debug.Log("Texture: " + snapshot.format);
cubeRenderer.material.mainTexture = snapshot;
snapCam.gameObject.SetActive(false);
}
}
string SnapshotName()
{
return string.Format("{0}/Resources/Snapshots/snap_{1}x{2}_{3}.png",
Application.dataPath, //Use application.persistent data path for player access
resWidth, resHeight, System.DateTime.Now.ToString("yyyy-mm-dd_HH-mm-ss"));
}
}