C# 如何比较数组中对象的位置?
所以我试着比较数组中一个对象的位置和我得到的int变量 我有一个叫做stagePos的变量,我想用它来找到一个对象,它在数组中的位置有相同的值 如果stagePos是1,那么我想找到一个在数组中位置为[1]的对象,并对其进行处理,同时对该数组中的另一个对象进行处理,因为它们与stagePos的值不同C# 如何比较数组中对象的位置?,c#,arrays,unity3d,C#,Arrays,Unity3d,所以我试着比较数组中一个对象的位置和我得到的int变量 我有一个叫做stagePos的变量,我想用它来找到一个对象,它在数组中的位置有相同的值 如果stagePos是1,那么我想找到一个在数组中位置为[1]的对象,并对其进行处理,同时对该数组中的另一个对象进行处理,因为它们与stagePos的值不同 if(stage[i] != stage[stagePos]){ Vector3 pos = stage[i].transform.position; pos += new Ve
if(stage[i] != stage[stagePos]){
Vector3 pos = stage[i].transform.position;
pos += new Vector3(0f, -4f * Time.deltaTime , 0f);
stage[i].transform.position = pos;
stageScript.Invinsible(true);
}
else if(stage[i] == stage[stagePos]){
Vector3 pos = stage[i].transform.position;
pos += new Vector3(0f, 4f * Time.deltaTime, 0f);
stage[i].transform.position = pos;
stageScript.Invinsible(false);
}
我希望代码只是坐在那里,等待stagePos值发生变化
因此,基本上您的代码没有问题,您只希望它是事件驱动的,而不是使用Update
。我们不知道如何以及在何处更改stagePos
的值,但我会使用如下方法
public void SetStagePos(int value)
{
// ignore if same value
if(stagePos == value) return;
stagePos = value;
for(var i = 0; i < stage.Length; i++)
{
// This could be actually done in one line
stage[i].transform.position += new Vector3(0f,(i == stagePos ? 1 : -1) * 4f * Time.deltaTime , 0f);
//Note: it is unclear where you want to go with the
//stageScript.Invisible()
// since currently you anyway call it for all objects
// so this will always end up with the value of
// stageScript.Invisible(i == stage.Length - 1);
}
}
或者,也可以将stagePos
作为一个具有支持字段的属性,如
private int _stagePos;
private int stagePos
{
get => _stagePos;
set =>
{
_stagePos = value;
for(var i = 0; i < stage.Length; i++)
{
stage[i].transform.position += new Vector3(0f,(i == stagePos? 1 : -1) * 4f * Time.deltaTime , 0f);
....
}
}
}
但是请注意一般来说,您对
Time.deltaTime
的使用只有在称为每帧的情况下才有意义
当然,这也取决于你如何获得你没有显示的用户输入。什么类型的对象是
stage
holding?如果(i==stagepos)…stage持有一个公共游戏对象[]stage;如果stagePos是一个int,您会遇到什么问题?如果stagePos是一个向量3,请通过stage.IndexOf(stagePos)
private int _stagePos;
private int stagePos
{
get => _stagePos;
set =>
{
_stagePos = value;
for(var i = 0; i < stage.Length; i++)
{
stage[i].transform.position += new Vector3(0f,(i == stagePos? 1 : -1) * 4f * Time.deltaTime , 0f);
....
}
}
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.NumPad1))
{
stagePos = 1;
}
//etc.
}