I am trying to take screenshots in game play and save them all into a folder.
this is my v basic code so far:
private float allowedScreenshots;
void Update () {
for (int i = 0; i < allowedScreenshots; i++)
{
if (Input.GetMouseButtonDown(1))
ScreenCapture.CaptureScreenshot(“Screenshot” + i + “.png”);
}
}
when i play the game it is saving the last screenshot and saving it as Screenshot9.png. I understand it is only saving the last thing and I need to be keeping them as the loop goes but I don’t know c# very well and I am stuck! Also the counter is going up even when I don’t click I think??
I am a complete novice, help is much appreciated!
The code that you have will take allowedScreenshots
number of screenshots of the same frame and always name them as “Screenshot#.png”, where # is a number less than allowedScreenshots
. This happens because you are taking screenshots in the same frame, because you call it in Update()
.
The correct approach is to store in the class the number of the last screenshot taken, and not use a loop at all::
public class ScreenShotter : MonoBehaviour {
[SerializeField] private int maxAllowedScreenshots = 1; // set it a value in the Editor
private int nextScreenshotIndex = 0;
private void Update () {
if (Input.GetmouseButtonDown(1) && nextScreenshotIndex < maxAllowedScreenshots) {
ScreenCapture.CaptureScreenshot("Screenshot" + nextScreenshotIndex + ".png");
nextScreenshotIndex++;
}
}
}
Btw, a recommendation: don’t use float
data type for numbers that should only be integer, it is sub-optimal and confusing. As there is no such thing as a partial index or screenshot, the screenshot number related variables should be int
.