You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity新手求助:基于外部数据源实现对象平移可视化移动

Fixing Data Extraction for Your Data-Driven Object Movement

Hey there! Let's work through this problem step by step—since you're new to programming, we'll break down what's off with your current code and build a more reliable solution to extract those Static Translation values.

First, Let's Identify the Issues in Your Code

Looking at your snippet, there are a few key problems that'll cause errors or unexpected behavior:

  • Array Index Out of Bounds: When you split the Static Translation line with Split(','), you'll get 3 elements (not 4), so using array[3] will throw an error.
  • Incorrect String Splitting Logic: Your current split steps don't properly clean up the parentheses and extra spaces around the numbers.
  • Unclosed Code Blocks: Your if statement and object initializer are missing closing braces, which will cause syntax errors.
  • No Boundary Checks: If i is near the end of the records array, i+1 or i+2 will go beyond the array length and crash your program.

Revised Solution: Reliable Value Extraction

Let's fix this with two approaches—one using basic string manipulation (easy to follow for beginners) and another using regex (more robust for varied formats).

Approach 1: Basic String Manipulation

This method directly targets the parentheses and cleans up the number values:

// Loop through records with safety to avoid index out of bounds
for (int i = 0; i < records.Length - 2; i++) 
{
    if (records[i].Contains("Parent: bp") && records[i + 1].Contains("Children(0):"))
    {
        string translationLine = records[i + 2];
        
        // Extract the part inside the parentheses
        int openParenIndex = translationLine.IndexOf('(') + 1;
        int closeParenIndex = translationLine.IndexOf(')');
        string valuesInsideParens = translationLine.Substring(openParenIndex, closeParenIndex - openParenIndex);
        
        // Split into individual number strings, removing empty entries and trimming spaces
        string[] valueParts = valuesInsideParens.Split(',', StringSplitOptions.RemoveEmptyEntries);
        
        // Safely parse the floats (use TryParse to avoid crashes if formatting is off)
        if (float.TryParse(valueParts[0].Trim(), out float x) &&
            float.TryParse(valueParts[1].Trim(), out float y) &&
            float.TryParse(valueParts[2].Trim(), out float z))
        {
            steps.Add(new Step() 
            { 
                speed = 2f, 
                destination = new Vector3(x, y, z) 
            });
        }
        else
        {
            // Handle invalid number formatting (log an error message, etc.)
            Console.WriteLine($"Could not parse values from line: {translationLine}");
        }
    }
}

Approach 2: Regular Expressions (More Robust)

If your dataset has slight variations in formatting, regex will handle it better by matching the exact pattern of numbers in parentheses:

using System.Text.RegularExpressions;

// Loop with safety checks
for (int i = 0; i < records.Length - 2; i++) 
{
    if (records[i].Contains("Parent: bp") && records[i + 1].Contains("Children(0):"))
    {
        string translationLine = records[i + 2];
        // Regex pattern to match three floating-point numbers inside parentheses
        Match valueMatch = Regex.Match(translationLine, @"\((-?\d+\.\d+), (-?\d+\.\d+), (-?\d+\.\d+)\)");
        
        if (valueMatch.Success)
        {
            float x = float.Parse(valueMatch.Groups[1].Value);
            float y = float.Parse(valueMatch.Groups[2].Value);
            float z = float.Parse(valueMatch.Groups[3].Value);
            
            steps.Add(new Step() 
            { 
                speed = 2f, 
                destination = new Vector3(x, y, z) 
            });
        }
        else
        {
            Console.WriteLine($"No valid translation values found in line: {translationLine}");
        }
    }
}

Key Tips for Your Workflow

  • Always Validate Input: Using TryParse instead of Parse prevents your program from crashing if the dataset has unexpected formatting.
  • Boundary Checks: The loop condition i < records.Length - 2 ensures we never try to access records[i+2] when i is too close to the end of the array.
  • Indentation & Closing Braces: Keeping your code properly indented helps catch missing braces early (most IDEs will highlight this for you!).

内容的提问来源于stack exchange,提问作者Göksel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:37:38