I’ve been using a jpeg encoder to take a screenshot of my game. The function which encodes the screenshot, aptly named EncodeScreenshot(filepath: String) is a generator function that is it contains a yield statement. The same javascript contains another function, getFilepath() which returns the filepath where the screenshot is stored.
From my gui script (written in C sharp), I can call getFilepath, no problem. But when I try to call EncodeScreenshot(filepath), it doesn’t appear to call the function. I have Debug.Log statements inside the function, and before and after the function call. The before and after statements print, but not the one inside the function.
On the other hand, if I write a test OnGui into the Screenshot script, the function saves the screenshot to the correct location.
What is happening? Why does one function call work and not the other? My wild guess is that it has something to do with the way generator functions work.
GUI Code abridged
void OnGui(){
if(submenuVisible = 1){
getScreenshot();
}
}
void getScreenshot(){
string filename = this.GetComponent<Screenshot>().ScreenShotName();
string message = "Your screenshot will be saved to: " + filename;
this.GetComponent<Screenshot>().ScreenshotEncode(filename);
GUI.BeginGroup(centerRect);
GUI.Box(new Rect(0, 0, centerRect.width, centerRect.height), message);
if(GUI.Button(new Rect((int)(centerRect.width/2 - 50), centerRect.height - 40, 100, 30), "OK")){
Debug.Log("Button true");
this.GetComponent<Screenshot>().ScreenshotEncode(filename);
Debug.Log("Picture stored?");
submenuVisible = -1;
}
GUI.EndGroup();
}
Screenshot Code in full
import System.IO;
private var filename : String;
/**
* Test key
*/
function OnGUI()
{
if(GUI.Button(new Rect(50, 50, 100, 100), "click")){
filename = ScreenShotName();
ScreenshotEncode(filename);
}
}
function Start(){
filename = "";
}
/**
* Take the screen buffer and spit out a JPG
*/
function ScreenshotEncode(filenameParameter: String)
{
Debug.Log("Start Encode");
filename = filenameParameter;
// wait for graphics to render
yield WaitForEndOfFrame();
// create a texture to pass to encoding
var texture:Texture2D = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);
// put buffer into texture
texture.ReadPixels(Rect(0.0, 0.0, Screen.width, Screen.height), 0.0, 0.0);
texture.Apply();
// split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy
yield;
// create our encoder for this texture
var encoder:JPGEncoder = new JPGEncoder(texture, 75.0);
// encoder is threaded; wait for it to finish
while(!encoder.isDone) {
yield;
}
// save our test image (could also upload to WWW)
File.WriteAllBytes(filename, encoder.GetBytes());
Debug.Log(String.Format("Took screenshot to: {0}", filename));
//return filename;
}
function ScreenShotName() {
return (Application.persistentDataPath + "/screen_" +
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") +".jpg");
}