Using Device Camera – Unity3D (C#)
You can get image from device camera in your scene to use for VR, player portrait etc. It’s pretty easy and tricky. Actually there is no object for device camera. We use the image captured from camera as material and display it on an object -mostly on a basic plane.
Just imagine that there is a white projector screen (plane object) in scene. We reflect the image on it. All objects are stable, but changing the angle of the camera makes a real camera effect.
Lets start with scene objects. Create a plane(with tag “Plane”), directional light and camera.
Place them as seems below.
As you see in preview window, scene camera is faced to plane and we get a view from toward.
Create a new C# script and start coding. First, add game objects.
1 2 |
public WebCamTexture camera; public GameObject plane; |
Then we need authorization to use the camera. Ask for it to device. Use “IEnumerator Start()” instead of default “void Start()”.
1 |
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); |
Initialization for texture and plane:
1 2 |
plane = GameObject.FindWithTag ("Plane"); camera = new WebCamTexture (); |
Now, get the image from device camera and reflect it on the plane.
1 2 |
plane.GetComponent<Renderer>().material.mainTexture = camera; camera.Play (); |
Run it! It will display the image on the plane what camera captures. Full code is below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class CamView : MonoBehaviour { private WebCamTexture camera; private GameObject plane; IEnumerator Start() { yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); plane = GameObject.FindWithTag ("Plane"); camera = new WebCamTexture (); plane.GetComponent<Renderer>().material.mainTexture = camera; camera.Play (); } } |
©Coffee Break Codes – Using Device Camera – Unity3D (C#)