I want to load sprite on json but how ? Text are showing but not the images.
This is the JSON code to load my text data.
private void myLoadGameData() /
Assuming questionImage
is a property in the myRoundData
variable, you would need to grab the string and use it as an asset path, Unity has a simple function to load assets by path
Resources.Load(string path)
This function will return a loaded asset reference as the provided generic type. However, the Resources.Load
method expects that all assets will be stored in a Resources
folder in the Assets
folder. You can have multiple Resources
folders nested within various other folders. For example, you could have the following files
Assuming their texture type is set to Sprite
, each one could be accessed with
Resources.Load("Test1");
Resources.Load("UI/Textures/Test2");
Resources.Load("Test3");
A few things to note
Resources
folder. (See Test2.png
in the
example above)With this approach, you first need to change the way you store your questionImage
property value to something like this
{ "questionImage":"NoentryPlate" }
Then, with the code you provided, we could add an additional method to handle this resource loading and sprite setting part. We would need a reference to a GameObject with a SpriteRenderer
component (you could create an empty gameObject and add the component yourself). Once you load the sprite, you can set the sprite
property of the SpriteRenderer
component to the sprite that you just loaded.
public SpriteRenderer MySprite;
private Sprite LoadedSprite = null;
private void myLoadGameData() //LOAD THE DATA
{
string myfilePath = Path.Combine(Application.streamingAssetsPath, mygameDataFileName); //I THINK THIS IS THE PATH OF THE FILE
if (File.Exists(myfilePath))
{
string mydataAsJson = File.ReadAllText(myfilePath); // READ THE FILE
TSGameData myloadedData = JsonUtility.FromJson(mydataAsJson); // TSGAME DATA IS A ANOTHER SCRIPT THAT HAVE AN ARRAY FOR THE DATA
myRoundData = myloadedData.myRoundData;
// vvv CALL OUR NEW METHOD HERE vvv
LoadSprite(myRoundData.questionImage);
} //myRoundData IS A VARIABLE THAT HOLDS THE ARRAY OF TSROUNDDATA TO GET THE DATA
else
{
Debug.LogError("Cannot load game data!");
}
}
private void LoadSprite (string path)
{
if (LoadedSprite != null)
Resources.UnloadAsset(LoadedSprite);
LoadedSprite = Resources.Load(path);
MySprite.sprite = LoadedSprite;
}