Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Resolved Screenshot didn't appear in the folder

Discussion in 'Scripting' started by Penny_Lu, Apr 11, 2022.

  1. Penny_Lu

    Penny_Lu

    Joined:
    Oct 28, 2019
    Posts:
    12
    I am trying to make an album with Unity. First, I want to save screenshots. My script is as follows. However, when I press the key "S" to take screenshot for the first time, it didn't appear in the folder except that I switch the window to wait for compiling. If I continue to press key, the subsequent screenshots will show correctly. I can't figure out why. Is there anyone can help me? Thank you!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.IO;
    5. using UnityEditor;
    6. using System;
    7.  
    8. public class TakeScreenshot : MonoBehaviour
    9. {
    10.      private int screenshotCount = 0;
    11.      private string screenshotFileName;
    12.      private string folderPath;
    13.      void Start()
    14.      {
    15.          folderPath = Application.dataPath + "/Resources/Textures/";
    16.          if (!System.IO.Directory.Exists(folderPath))
    17.             System.IO.Directory.CreateDirectory(folderPath);
    18.      }
    19.    
    20.      void Update()
    21.      {                    
    22.         if (Input.GetKeyDown(KeyCode.S))
    23.          {
    24.              StartCoroutine(CaptureScreenshot());          
    25.          }
    26.      }
    27.  
    28.      private IEnumerator CaptureScreenshot()
    29.      {
    30.           screenshotCount ++;
    31.           screenshotFileName = "Screenshot_" + screenshotCount + ".png";
    32.           ScreenCapture.CaptureScreenshot(folderPath + screenshotFileName);
    33.           AssetDatabase.Refresh();
    34.           yield return new WaitForEndOfFrame();
    35.      }
    36.    
    37. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    This script uses
    UnityEditor
    so keep in mind it will not build to your final game. You would need to guard out the UnityEditor code with #if UNITY_EDITOR checks.

    Line 33 appears to be the correct refresh call. Have you tried inserting a
    yield return null;
    statement just before it?
     
  3. Penny_Lu

    Penny_Lu

    Joined:
    Oct 28, 2019
    Posts:
    12
    It works! Thanks a lot!