- Home /
WebCamTexture on a SpriteRenderer
I recently have been trying to get the WebCamTexture to work on a sprite. Thinking it was going to be as straightforward as the sample code, i tried
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Start() {
WebCamTexture webcamTexture = new WebCamTexture();
renderer.material.mainTexture = webcamTexture;
webcamTexture.Play();
}
}
But this didn't do anything at all. Any suggestions?
Answer by Katchy · Jun 19, 2014 at 05:45 PM
Your first problem is that you need switch lines 7 and 8 like this:
WebCamTexture webcamTexture = new WebCamTexture();
webcamTexture.Play();
renderer.material.mainTexture = webcamTexture;
The reason being: webcamTexture.Play() will start the camera feed to Unity. If you set the material before starting the camera, you won't have any texture to set the material to! [edit: you'll also want to make sure your camera is running, usually indicated by a tiny red or green light next to the camera, before you play the game]
And, as robertbu suggests, try using a quad, plane, or other type of gameobject for this. As far as I know, if you're using sprites you can set the sprite material easily enough by using the following code:
gameObject.GetComponent<SpriteRenderer> ().material.mainTexture = webcamTexture;
but, this will change the entire sprite sheet to be the camera output instead of a single sprite. For more info on Sprites, check out Unity's API: http://docs.unity3d.com/ScriptReference/Sprite.html
Hope this helps!
Answer by deanpackard · Aug 29, 2018 at 09:45 PM
The answer above didn't quite work for me, but it is very close.
Instead of
gameObject.GetComponent<SpriteRenderer> ().material.mainTexture = webcamTexture;
I did
gameObject.GetComponent<Image> ().material.mainTexture = webcamTexture;