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

Unity C#技术求助:计数超6时实现对象同排X轴平移

Unity C#开发问题:同色计数超6时对象X轴平移异常

我在Unity用C#开发时碰到个棘手的问题——需求是当newPrevious值(可选BLUE、RED、GREEN)对应的计数超过6时,自动把对象在同一行的X轴方向平移一个单位。

预期效果

预期效果:同色数量超过6个后,在同一行X轴方向依次排列

初始实现的实际效果

初始实际效果:同色数量超过6个后未正确进行X轴平移

我的原代码

string[,] table = new string[104, 6]; 
int xIndex = -1; 
int yIndex = 0; 
int counter = 0; 

if (table.GetLength(0) < xIndex) { 
    break; 
} 

if (result.Equals(newPreviousValue) && yIndex < table.GetLength(1)) { 
    yIndex += 1; 
    counter++; 
    table[xIndex, yIndex] = result; 
} else { 
    xIndex += 1; 
    yIndex = 0; 
    counter = 0; 
    table[xIndex, yIndex] = result; 
} 

if (result.Equals("T") && yIndex < table.GetLength(1)) { 
    yIndex += 1; 
    table[xIndex, yIndex] = result; 
} 

newPreviousValue = result; 

// 设置对象新位置
if (counter < 6) { 
    bigroad.transform.localPosition = new Vector3(xIndex * 19, yIndex * -19, 0f); 
} else { 
    bigroad.transform.localPosition = new Vector3(xIndex * 19, yIndex * -95, 0f); 
} 

之后我尝试了Ignacio提供的代码,结果又出现了预制体位置重叠的问题:

修改后的代码(Ignacio提供)

if (counter > 6) { 
    xIndex2 += 1; 
    yIndex2 = 0; 
    table[xIndex2, yIndex2] = result; 
} 

if (counter < 6) { 
    bigroad.transform.localPosition = new Vector3(xIndex * 19, yIndex * -19, 0f); 
} else { 
    int reminder = counter % 6; 
    bigroad.transform.localPosition = new Vector3((xIndex2 + reminder) * 19, -95, 0f); 
} 

修改后的异常效果

修改后效果:预制体出现位置重叠

真心希望各位大佬能帮我解决这个问题!

内容的提问来源于stack exchange,提问作者Ginxxx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:58:24