[英](UNITY) My JSON file is not loading on start
I am making a basic shop system includes car name, price and buyable.我正在制作一个基本的商店系统,包括汽车名称、价格和可购买性。 I am saving data to a text file.我正在将数据保存到文本文件。 When I replay, I can't get the last variables I've changed.当我重播时,我无法获得我更改的最后一个变量。 But, if I refresh at Editor by CTRL+R and start the game, variables are loading correct.但是,如果我通过 CTRL+R 在编辑器中刷新并启动游戏,则变量加载正确。 What am I doing wrong?我究竟做错了什么? I am new at storage and JSON issues.我是存储和 JSON 问题的新手。 Thanks for answers...谢谢你的回答...
Here is the code:这是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class GameHandler : MonoBehaviour
{
[Serializable]
public class Car
{
public string name;
public int price;
public bool unlocked;
}
[Serializable]
public class CarList{
public Car[] cars;
}
private Car cars = new Car();
public CarList myCars = new CarList();
//-------
public int chosenCar;
//-------
public TextAsset CARS;
//-------
private void Start() {
GetFromJSON();
}
private void Update() {
if(Input.GetKeyDown(KeyCode.L))
GetFromJSON();
if(Input.GetKeyDown(KeyCode.S))
SaveToJSON();
}
public void ChangeCarIndex(int a){
chosenCar = a;
}
//This is a button func.
public void ChangePrice(int a){
myCars.cars[chosenCar].price = a;
SaveToJSON();
}
public void GetCarName(){
Debug.Log(myCars.cars[chosenCar].name);
}
public void GetCarPrice(){
Debug.Log(myCars.cars[chosenCar].price);
}
public void SaveToJSON(){
string jsOutput = JsonUtility.ToJson(myCars);
File.WriteAllText(Application.dataPath + "/CARS.txt", jsOutput);
Debug.Log("SaveToJSON() called");
}
public void GetFromJSON(){
myCars = JsonUtility.FromJson<CarList>(CARS.text);
Debug.Log("GetFromJSON() called");
}
}
When running this in the editor try to add在编辑器中运行时尝试添加
public void SaveToJSON()
{
string jsOutput = JsonUtility.ToJson(myCars);
File.WriteAllText(Application.dataPath + "/CARS.txt", jsOutput);
Debug.Log("SaveToJSON() called");
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();
#endif
}
Though actually this isn't really necessary!虽然实际上这不是真的必要! Afaik you could also simply set the text of the textasset: Afaik 你也可以简单地设置 textasset 的文本:
public void SaveToJSON()
{
string jsOutput = JsonUtility.ToJson(myCars);
CARS.text = jsOutput;
Debug.Log("SaveToJSON() called");
}
BUT NOTE:但请注意:
in general note that this makes only sense in the editor itself.通常请注意,这仅对编辑器本身有意义。
If you target to do this in an actually later built application you would rather go via a file in Application.persistentataPath
.如果您的目标是在稍后构建的实际应用程序中执行此操作,您宁愿通过Application.persistentataPath
的文件进行操作。 Problem with that though: The data can easily be seen and edited by the user.但问题是:用户可以轻松查看和编辑数据。 So if this is anything sensitive you will need to go for a central database server with user login.因此,如果这是任何敏感信息,您将需要使用用户登录的中央数据库服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.