Chapter 13. Files, Networking, and Screenshots
Rich, complex, visual computer programs, like the sort of thing you might make with Unity, also need to do mundane, traditional computer things, like saving, loading, and parsing files. We’ve saved the most thrilling chapter for last: here you’ll find recipes for saving screenshots, state, and textures, as well as for importing files using a custom pipeline. Utterly thrilling (not really), but utterly essential (really!).
13.1 Saving Files
Problem
You want to know where you can save files that your project generates, like screenshots and saved games.
Solution
Use the Application.persistentDataPath
property to get the location of a folder to which you can save data:
public
string
PathForFilename
(
string
filename
)
{
// Application.persistentDataPath contains a path where we can
// safely store data
var
folderToStoreFilesIn
=
Application
.
persistentDataPath
;
// System.IO.Path.Combine combines two paths, using the current
// system's directory separator ( \ on Windows, / on just about
// every other platform)
var
path
=
System
.
IO
.
Path
.
Combine
(
folderToStoreFilesIn
,
filename
);
return
path
;
}
Discussion
The directory provided by persistentDataPath
is not guaranteed to be exposed to the user; for example, it won’t be exposed on mobile platforms where the user doesn’t have direct access to the filesystem.
13.2 Saving an Image File of Your Game to Disk
Problem
You want to capture an image of your game (a screenshot), and save it to ...
Get Unity Development Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.