When rendering webcam as textures, Unity3D ships with a useful WebCamTexture class, the typical use of this class is as follows:
- Create a GUITexture object: in unity menu: GameObject Create Other GUI Texture, let’s name it CamTexture;
- Create a C# script, let’s also name it CamTexture.cs
- In the script, create an instance of WebCamTexture:
- In the Start() function, add below code:
webcamTexture = new WebCamTexture();
guiTexture.texture = webcamTexture;
- Drag CamTexture.cs to the CamTexture game object in Unity3d; build and run the app in your android device;
- When you run the application, you will see very small camera view shown in your device, this is because when you create the CamTexture game object, you did not set the Pixel Inset values and default values are used instead:
- Let’s make the GUI texture to be rendered in full screen mode, in the Start() function, add below code lines to the top of the function body:
float W = Screen.width;
float H = Screen.height;
float InsetX = -( W / 2) ;
float InsetY = -( H / 2) ;
guiTexture.pixelInset = new Rect(InsetX, InsetY, W, H);
Build and re-run the app, you will find that webcam is rendered in full screen, but the textures seem to be rendered with 90 degree rotations and possibly some flips:
To solve this, you can change the Player Settings during the app build process
–> Press Ctrl + Shift + B or click menu File Build Settings… ,
–> Click the “Player Settings…” button, and Unity3D inspector shows a panel, as shown below.
–> Choose whichever settings under “Resolution and Presentation” category, e.g. “LandScape Left”
–> Rebuild and run the app. Oh yeah, yeah… it worked now!
It was noted by many other posts that, if this does not work, you can add below line on a trial and error basis:
guiTexture.transform.localScale = new Vector3(-1,-1,1);
The entire code looks as below. Happy coding and enjoy!