首页 > 解决方案 > 知道函数何时完成处理

问题描述

我试图进行屏幕截图,但我不想包含某些画布。我尝试了下面的代码,但画布仍然包含在捕获中。在执行下一行代码之前如何知道截屏功能何时完成?

void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                GameManager.Instance.memeButton.SetActive(false);
                ScreenCapture.CaptureScreenshot("C:/Users/jamjam/dwhelper/Desktop/test/jamjam.png");
                GameManager.Instance.memeButton.SetActive(true);
            }
            
        }

标签: c#unity3d

解决方案


ScreenCapture.CaptureScreenshot

CaptureScreenshot立即在 Android 上返回。屏幕截图在后台继续。几秒钟后,生成的屏幕截图将保存在文件系统中。

=> 没有关于它在 PC 上的行为的真正信息。所以基本上没有内置的方法可以知道它何时完成,这在所有平台上都有效......但是你可以构建一个协程来检查它,例如

private bool alreadyTakingScreenshot;

void Update()
{
    if (!alreadyTakingScreenshot && Input.GetKeyDown(KeyCode.Space))
    {
        // Start a new routine
        StartCoroutine(ScreenshotRoutine);
    }   
}

// or in case you do NOT want the GUI to appear in your screenshot (see comment in ScreenshotRoutine)
//void LateUpdate()
//{
//    if (!alreadyTakingScreenshot && Input.GetKeyDown(KeyCode.Space))
//    {
//        // Start a new routine
//        StartCoroutine(ScreenshotRoutine);
//    }   
//}

private void IEnumerator ScreenshotRoutine()
{
    if(alreadyTakingScreenshot) yield break;

    alreadyTakingScreenshot = true;

    GameManager.Instance.memeButton.SetActive(false);

    // It is convenient to wait until the end of the frame which is right
    // before the frame is rendered by the camera
    // If you don't want the GUI to appear in your screenshot then
    // remove this and rather start the routine from LateUpdate
    yield return new WaitForEndOfFrame();
    

    // Use a timestamp so everytime a new image is created
    var dateStamp = DateTime.Now.ToString("yyyy-dd-M_HH-mm-ss");
    var path = @"C:/Users/jamjam/dwhelper/Desktop/test/jamjam_" + dateStamp + ".png";

    // Or alternatively simply delete the exsting file as you will overwrite it
    //var path = @"C:/Users/jamjam/dwhelper/Desktop/test/jamjam.png"
    //if(!File.Exists(path))
    //{
    //   File.Delete(path);    
    //}

    // start the capture
    ScreenCapture.CaptureScreenshot(path);

    // Wait until the according file is actually created
    while(!File.Exists(path))
    {
        yield return null;
    }

    GameManager.Instance.memeButton.SetActive(true);

    alreadyTakingScreenshot = false;
}

推荐阅读