【问题标题】:C# using simpleJSON to get a random objectC#使用simpleJSON获取随机对象
【发布时间】:2020-06-27 20:54:58
【问题描述】:

我想在下面的 json 中的 BodyPresets 中获取一个随机对象。 我使用它是因为它易于理解,并且它成功地为我获取了一个字符串。

{
    "BodyPresets":[
    {  
       "name":"bodypreset1",
       "height": {"x":0.3, "y":0.5},
       "upper_arms": {"x":0.3, "y":0.5},
       "lower_arms": {"x":0.3, "y":0.5}
    },
    {  
       "name":"bodypreset2",
       "height": {"x":0.5, "y":0.7},
       "upper_arms": {"x":0.5, "y":0.7},
       "lower_arms": {"x":0.5, "y":0.7}
    },
    {  
       "name":"bodypreset3",
       "height": {"x":0.7, "y":0.9},
       "upper_arms": {"x":0.7, "y":0.9},
       "lower_arms": {"x":0.7, "y":0.9}
    }
    ]
}

在下面的 C# 代码中,我尝试了但只收到了 CS0121 错误:

using SimpleJSON;

    void RandomiseCharBody()
    {
        var dllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string configFilename = "Randomizer.json";
        var configPath = Path.Combine(dllPath, configFilename);
        
        //// from https://answers.unity.com/questions/1473952/how-to-write-and-read-json-in-unity.html  
        //// https://github.com/Bunny83/SimpleJSON
        string jsonString = File.ReadAllText(configPath); 
        JSONNode data = JSON.Parse(jsonString);
        JSONNode BodyPresets = data["BodyPresets"];
        
        //attempt at gettting a random preset from the list
        var randompreset = BodyPresets[UnityEngine.Random.Range(0, BodyPresets.Count)];
        JSONNode preset = BodyPresets[randompreset];

        float min1 = preset["height"]["x"];
        float min2 = preset["upper_arms"]["x"];
        float min3 = preset["lower_arms"]["x"];
        
        float max1 = preset["height"]["y"];
        float max2 = preset["upper_arms"]["y"];
        float max3 = preset["lower_arms"]["y"];
        
        // applies the values
        shapeValueBody[0] = UnityEngine.Random.Range(min1, max1);
        shapeValueBody[1] = UnityEngine.Random.Range(min2, max2);
        shapeValueBody[2] = UnityEngine.Random.Range(min3, max3);
    }   

但是如何做到这一点呢?

【问题讨论】:

  • 你能把错误的全文贴出来吗?
  • @Abion47 错误 CS0121 调用在以下方法或属性之间不明确:'JSONNode.this[int]' 和 'JSONNode.this[string]' Randomizer
  • 您在哪一行收到此错误?
  • @OnionFan 在 JSONNode 预设 = BodyPresets[randompreset];
  • 但在这一行 - var randompreset = BodyPresets[UnityEngine.Random.Range(0, BodyPresets.Count)]; - 你已经得到了随机预设,不是吗?在这一行中,您尝试使用对象进行预设 - JSONNode preset = BodyPresets[randompreset];,奇怪的行为

标签: c# json unity3d simplejson


【解决方案1】:

这不是必需的:

JSONNode preset = BodyPresets[randompreset];

因为

var randompreset = BodyPresets[UnityEngine.Random.Range(0, BodyPresets.Count)];

已经得到一个随机对象。

感谢@OnionFan

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多