- Home /
unable to cast from source to destination
here is my code i am again and again getting cast exception ...please help me in this code ..i am trying to capture an image and then show it ...i have used gameobject cube on which i am streaming the camera feed .here is the code
using UnityEngine;
using System.Collections;
public class Selfie : MonoBehaviour {
public string deviceName;
WebCamTexture wct;
// Use this for initialization
void Start ()
{
WebCamDevice[] devices = WebCamTexture.devices;
deviceName = devices [0].name;
wct = new WebCamTexture (deviceName, 400, 300, 12);
renderer.material.mainTexture = wct;
wct.Play ();
}
//for photo variables
public Texture2D heightmap;
public Vector3 size= new Vector3(100,10,100);
void OnGUI()
{
if (GUI.Button (new Rect (10, 70, 50, 30), "click"))
TakeSnapshot ();
}
//for saving to the _savepath
private string _SavePath= "D:/WebcamSnaps/" ;
int _CaptureCounter = 0;
void TakeSnapshot()
{
Texture2D snap = new Texture2D (wct.width, wct.height);
snap.SetPixels (wct.GetPixels ());
snap.Apply ();
//byte[] bytes = snap.EncodeToPNG ();
System.IO.File.WriteAllBytes(_SavePath + _CaptureCounter.ToString() + ".png", snap.EncodeToPNG());
++_CaptureCounter;
WWW www = new WWW ("file://D:/WebcamSnaps/0.png");
while (!www.isDone)
www.LoadImageIntoTexture((Texture2D)renderer.material.mainTexture) ;
}
}
Search the error message, and look for some intro book on program$$anonymous$$g/scripting. Hopefully that will explain what casting is, and how to find the line with the error.
Thanks for the help..sorry for late reply ..the issue have been solved.
Answer by DiegoSLTS · Mar 08, 2015 at 05:15 PM
Please, share the error you see, not just some words from it. If you have a cast exception it probably says why it can't make the cast.
Also, note that this:
while (!www.isDone)
www.LoadImageIntoTexture((Texture2D)renderer.material.mainTexture);
will try to load the downloaded image into a texture every frame while the request has not finished. Even if there wasn't a cast error, this line will throw an exception.
You probably want to write this code instead:
while (!www.isDone) {} // not the brakets, the next line will be called ONLY after the request finishes
www.LoadImageIntoTexture((Texture2D)renderer.material.mainTexture);
But this is really a bad idea, the game will freeze until the request ends. You should make this method a coroutine and yield until the request is done.
Your answer
Follow this Question
Related Questions
Cannot cast from source to destination type 1 Answer
InvalidCastException: Cannot cast from source type to destination type. 3 Answers
"Cannot cast from source type to destination type" 2 Answers
Unable to cast from the source? 1 Answer
"Cannot cast from source type to destination type"- instantiating 4 Answers