如何循环列表中的下一项?
How can I cycle the next item in my list?
我正在为一个统一项目构建墙放置脚本,您可以在其中放置 posts,如果 post 离另一个 post 足够近,墙将在两者之间实例化他们。我遇到的问题是循环列表中的对象以找到确定距离的 2 个对象,currentPost 和 previousPost。
[SerializeField]
private GameObject wall;
[SerializeField]
private GameObject post;
public GameObject currentPost;
public GameObject previousPost;
private List<GameObject> posts = new List<GameObject>();
private void Update()
{
GetInput();
Debug.Log(posts.Count);
Debug.Log("Distance" + Distance());
}
private void AdjustWalls()
{
previousPost = posts[0]; //here is where I'm hoping to make the cycling change
if(Distance() > 10)
{
Debug.Log("wall Placed");
}
}
private void AddPosts()
{
currentPost = ((GameObject)Instantiate(post, gridSnap(getWorldPoint()), Quaternion.identity));
posts.Add(currentPost);
AdjustWalls();
}
private void GetInput()
{
if (Input.GetKeyDown("q"))
{
AddPosts();
currentPost.transform.parent = transform;
}
}
public float Distance()
{
return Vector3.Distance(currentPost.transform.position, previousPost.transform.position);
}
感谢任何帮助。
您不能在 AddPost
中执行此操作,而是执行以下操作并从 AdjustWalls()
中删除 previousPost = posts[0];
行吗?:
private void AddPosts()
{
if(currentPost != null)
{
previousPost = currentPost;
}
currentPost = ((GameObject)Instantiate(post, gridSnap(getWorldPoint()), Quaternion.identity));
posts.Add(currentPost);
AdjustWalls();
}
我正在为一个统一项目构建墙放置脚本,您可以在其中放置 posts,如果 post 离另一个 post 足够近,墙将在两者之间实例化他们。我遇到的问题是循环列表中的对象以找到确定距离的 2 个对象,currentPost 和 previousPost。
[SerializeField]
private GameObject wall;
[SerializeField]
private GameObject post;
public GameObject currentPost;
public GameObject previousPost;
private List<GameObject> posts = new List<GameObject>();
private void Update()
{
GetInput();
Debug.Log(posts.Count);
Debug.Log("Distance" + Distance());
}
private void AdjustWalls()
{
previousPost = posts[0]; //here is where I'm hoping to make the cycling change
if(Distance() > 10)
{
Debug.Log("wall Placed");
}
}
private void AddPosts()
{
currentPost = ((GameObject)Instantiate(post, gridSnap(getWorldPoint()), Quaternion.identity));
posts.Add(currentPost);
AdjustWalls();
}
private void GetInput()
{
if (Input.GetKeyDown("q"))
{
AddPosts();
currentPost.transform.parent = transform;
}
}
public float Distance()
{
return Vector3.Distance(currentPost.transform.position, previousPost.transform.position);
}
感谢任何帮助。
您不能在 AddPost
中执行此操作,而是执行以下操作并从 AdjustWalls()
中删除 previousPost = posts[0];
行吗?:
private void AddPosts()
{
if(currentPost != null)
{
previousPost = currentPost;
}
currentPost = ((GameObject)Instantiate(post, gridSnap(getWorldPoint()), Quaternion.identity));
posts.Add(currentPost);
AdjustWalls();
}