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() /
To be a valid JSON, your text file content should be inside brackets, like this:
{ "questionImage":"Assets/ImagesQuiz/NoentryPlate.png" }
Please check JSON format documentation here.
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<T>(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<Sprite>("Test1");
Resources.Load<Sprite>("UI/Textures/Test2");
Resources.Load<Sprite>("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<TSGameData>(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<Sprite>(path);
MySprite.sprite = LoadedSprite;
}
You should check the documentation on loading images, also try using breakpoints to see whats being fed into the function and if that path actually exists (it looks like an absolute path, and if so most likely not going to work)
I imagine if there was a problem with the JSON you would get the relevant error about it, but seems more like miss-use of the function and/or improper file path