如何在Unity中读取JSON文件的Speed参数并控制角色移动
实现从JSON读取Speed参数控制Unity角色移动
需求说明
需要读取指定JSON文件中的Speed参数,将其作为Unity Inspector可配置参数,以此控制Agent或角色的移动速度,目前已完成基础JSON读取脚本,需补充移动控制逻辑。
待读取的JSON文件内容
{ "player": [ { "X":7.214575709504705, "Z":28.484783109249697, "ID":"116", "Speed":1.0 } ] }
当前已编写的JsonReader脚本
using System.Collections.Generic; using UnityEngine; public class Reader : MonoBehaviour { public TextAsset jsonData; public PlayerList players = new PlayerList(); [System.Serializable] public class Player { public float X; public float Z; public string ID; public float Speed; } [System.Serializable] public class PlayerList { public Player[] player; } // Start is called before the first frame update void Start() { players = JsonUtility.FromJson<PlayerList>(jsonData.text); } }
实现步骤
1. 读取并暴露Speed参数到Inspector
在Reader类中添加公开字段存储当前速度,在Start方法中从JSON读取赋值,这样参数会显示在Inspector中,方便查看或临时调整:
public float currentSpeed; // 该字段会显示在Inspector面板 void Start() { players = JsonUtility.FromJson<PlayerList>(jsonData.text); // 读取数组中第一个玩家的Speed值(可根据需求按ID筛选) if(players.player != null && players.player.Length > 0) { currentSpeed = players.player[0].Speed; } }
2. 添加角色移动控制逻辑
根据角色使用的组件(CharacterController/Rigidbody)编写移动代码,以下是基于CharacterController的示例:
using UnityEngine; public class Reader : MonoBehaviour { public TextAsset jsonData; public PlayerList players = new PlayerList(); public float currentSpeed; private CharacterController controller; [System.Serializable] public class Player { public float X; public float Z; public string ID; public float Speed; } [System.Serializable] public class PlayerList { public Player[] player; } void Start() { // 获取角色的CharacterController组件 controller = GetComponent<CharacterController>(); players = JsonUtility.FromJson<PlayerList>(jsonData.text); if(players.player != null && players.player.Length > 0) { currentSpeed = players.player[0].Speed; } } void Update() { // 用WASD控制角色移动,速度由JSON读取的currentSpeed决定 float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 moveDir = transform.right * horizontal + transform.forward * vertical; controller.Move(moveDir * currentSpeed * Time.deltaTime); } }
3. 注意事项
- 确保JSON文件在Unity中被设置为
TextAsset类型(选中文件后,Inspector的Import Settings设为Text) - 若角色使用Rigidbody组件,需将移动逻辑改为修改
rigidbody.velocity,避免与CharacterController冲突 - 若JSON包含多个Player对象,可通过遍历数组匹配ID来获取对应角色的Speed值
内容的提问来源于stack exchange,提问作者ambioss
相关产品推荐
相关产品推荐

