GetFile
Last updated
Last updated
The GetFile method is a method which lets you get a file using a string instead of directly accessing a file. In other words, if a screen or entity contains a file called Bear.png, GetFile allows you to do this from within the screen or entity:
The argument (in the example above "Bear") matches the name of the variable in the screen or entity. This will usually be the name of the file, without any path or extension. The exception to this rule is if the IncludeDirectoryRelativeToContainer value is true. Similary, GetFile can be called to obtain files from GlobalContent. For example, the following returns a song called BattleSong from GlobalContent:
Using the example above, you can simply do:
However, if you need to dynamically select a texture (such as if you are reading information from a CSV) your code may need to be dynamic. Therefore, you could do:
Another common example is that a game may support loading levels dynamically, as follows:
GetFile will usually work without any additional code most of the time, but not always. We'll look at two different scenarios and discuss what is required for each:
The most common - and simplest - scenario is calling GetFile when there is already an instance of the object that holds the files created. This can be done in a number of ways:
Calling a screen's GetFile function when the Screen is the active Screen
Calling an entity's GetFile function from within the entity's custom Initialize/Activity/LoadStaticContent methods
Calling an entity's GetFile function through an instance of that entity
In all of the above cases, an instance of that Screen/entity will have been created, meaning that the files will have been loaded and are available to access through GetFile. In short, if an instance is alive, then GetFile should work without any other code.
It is possible to call GetFile on a screen/entity without having an instance of that screen/entity. However, to do this, you must first tell the screen/entity to load the files so that they are available through GetFile. For example, consider the following code:
LoadStaticContent can be called multiple times, and this will not reload the content as long as the same content manager is used. For more information, see the LoadStaticContent page.