Setup: Unity 2019
I am trying to get the texture from a plane.
I capture the camera input and map it on a plane. Then i want to read the texture continuously.
I tried something like this. PS: I am new with unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraInput : MonoBehaviour
{
static WebCamTexture backCam;
void Start()
{
if (backCam == null)
backCam = new WebCamTexture();
GetComponent<Renderer>().material.mainTexture = backCam;
if (!backCam.isPlaying)
backCam.Play();
}
void Update()
{
byte[] bytes = GetComponent<Renderer>().material.mainTexture.EncodeToPNG();
System.IO.File.WriteAllBytes(path, bytes);
Debug.Log(bytes.Length/1024 + "Kb was saved as: " + path);
}
}
Error received:
Unable to retrieve image reference UnityEngine.ImageConversion:EncodeToPNG(Texture2D)
Webcam is a Texture and you can encodetopng Texture2d. So the solution to this is:
Texture2D tex = new Texture2D(backCam.width, backCam.height);
tex.SetPixels(backCam.GetPixels());
tex.Apply();
byte[] bytes = tex.EncodeToPNG();