【问题标题】:How to store a Vector3 list in a string Unity c#如何将 Vector3 列表存储在字符串 Unity c#
【发布时间】:2021-11-22 14:47:18
【问题描述】:

我真的不知道如何开始编写这个程序,我想使用字符串系统而不是列表系统的原因是因为列表系统在我的电脑上占用了太多的内存,落后于整个游戏。 (我有 16 GB 内存)

这也是我希望它工作的方式:假设我有一个标记为“1\n”、“2\n”、“3\n”、“4\n”、“5\n”、“ 6\n" 那么如果我想得到的字符串的索引是 = 0。我会得到一个 vector3 = 1, 2, 3 如果索引为 1,则为 4, 5,6。

如果您知道解决此问题的任何其他方法,我们将不胜感激。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Container : MonoBehaviour
{
    public string Bchanged;

    void GetBlockbyIndex(int index)
    {
        //Get what block it is based on its index 
        /*Example:
         * index = 0;
         * Bchanged = "1\n", "2\n", "3\n", "4\n", "5\n", "6\n";
         * Vector3 answer = new vector3(1, 2, 3);
         */
        Vector3 anwser = Bchanged[index];
    }
    void AddBlock(Vector3 block)
    {
        //Add block to string list
    }
}

【问题讨论】:

  • 你在做什么,列表滞后?没有真正的好方法来做到这一点。将数据存储在字符串中,您仍然需要在分隔符上将其拆分,将其打包为更标准的格式(如 JSON)或填充所有内容以在索引之间具有一致的长度。访问和使用子字符串比仅访问列表中的向量要慢得多。按索引访问列表是 O(1)。如果顺序无关紧要,您可以将删除替换为 O(1),将添加替换为 O(1)。
  • 它需要保存一个字符串的一个重要原因是将来我希望它能够联网,并且联网字符串比联网列表更容易同步。我也想使用播放器偏好来保存数据。
  • 然后使用 JSON。没有理由重新发明轮子。在运行时使用 vec3 列表,然后在需要时序列化。您也可以通过网络发送 vec3。
  • 我的家伙这更容易根据我的游戏代码的其余部分是如何工作的,我从 Strom 找到了答案。
  • 如果这是真的,那么祝你好运。

标签: c# arrays string list unity3d


【解决方案1】:

在字符串中编码数据将使用比 Vector3 更多的内存。 一个 Char 是 16 位。 16 *(3 个数字 + 2 个分隔符)= 80 位。 一个 Vector3 是 3 个浮点数 = 96 位,可以存储超过 0-9 个。

列表在数组之上增加了一点开销,但让您能够动态添加空间。

如果您知道要添加多少项目,请使用初始容量参数:

List<Vector3> Blocks = new List<Vector3>(100); 这将防止底层数组的大小重新分配。


如果你的值都是正整数并且X,Y,Z的范围= (0,0,0) - (2047,2047,1023),你可以节省三分之一的空间

您可以将 Vector3 存储在压缩无符号整数(32 位)中。

List<UInt32> Blocks = new List<UInt32>(); // insert max count if known

const int SCALE = 1; 
// for Grid alignment(16 makes the stored values 1, 2,... 2047 -> 16, 32,... 32752)

Vector3 GetBlockbyIndex(int index)
    {
        //Get what block it is based on its index 
        
        return new Vector3(Blocks[index] & 0x7FF, 
                          (Blocks[index] & 0x3FFFFF) >> 11, 
                          Blocks[index] >>22) * SCALE;
    }
    void AddBlock(Vector3 block)
    {
        //Add block to list
        // Watch the input range, (2048,0,0) becomes (0,1,0)
        block /= SCALE;
        Blocks.Add((uint)block.X | (uint)block.Y << 11 | (uint)block.Z << 22);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多