Unity新手求助:基于外部数据源实现对象平移可视化移动
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 usingarray[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
ifstatement and object initializer are missing closing braces, which will cause syntax errors. - No Boundary Checks: If
iis near the end of therecordsarray,i+1ori+2will 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
TryParseinstead ofParseprevents your program from crashing if the dataset has unexpected formatting. - Boundary Checks: The loop condition
i < records.Length - 2ensures we never try to accessrecords[i+2]wheniis 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

