unity3d c# -UNITY中随机传送位置的嵌套循环

iyr7buue  于 2023-02-23  发布在  C#
关注(0)|答案(1)|浏览(187)

我尝试在Unity中按特定顺序将一个物体传送到不同的位置,但系统没有通过嵌套循环到达下一个传送位置。我在2d数组中预先分配了传送位置,希望系统通过嵌套循环遍历2d数组并相应地移动物体。但它只是将对象移动到SP3位置,而不考虑track_teleporation_index中的元素。所以我假设嵌套的for循环中的if-else if语句有错误,但作为编码和Unity的初学者,经过几天的故障排除,我还是想不出解决办法。
任何帮助或领导将不胜感激!
她就是我的密码:

public class Teleporting : MonoBehaviour
{
    public GameObject mouse;
    public Transform SP1; //Starting Position in Track 1
    public Transform SP2; //Starting Position in Track 2
    public Transform SP3; //Starting Position in Track 3
    private int[,] track_teleportation_index;

    void OnTriggerEnter(Collider other)
    {
        mouse = GameObject.Find("mouse");

        track_teleportation_index = new int[3, 3] { { 1,2,3 }, { 3, 1, 2 }, { 1, 2, 3 } }; 

        for (int row = 0; row < track_teleportation_index.GetLength(0); row++)
            for (int col = 0; col < track_teleportation_index.GetLength(1); col++)
            {
                if (track_teleportation_index[row, col] == 1)
                {
                    mouse.transform.position = SP1.transform.position;
                }
                else if (track_teleportation_index[row, col] == 2)
                {
                    mouse.transform.position = SP2.transform.position;
                }
                else if (track_teleportation_index[row, col] == 3)
                {
                    mouse.transform.position = SP3.transform.position;
                }

                Debug.Log("Teleported to track #" + track_teleportation_index[row, col]);
            }
    }

}
slmsl1lt

slmsl1lt1#

如果我没理解错的话

  • 第一次按下触发器-〉转到SP1
  • 第二次按下触发器-〉转到SP2
  • 第三次按下触发器-〉转到SP3
  • 第四次按下触发器-〉转到SP1
  • 等等

一个计数器就足够了

// Simply reference as many target Transform as you need
public Transform[] SPS;

// index for the NEXT target
private int index;

void OnTriggerEnter(Collider other)
{
    // is the mouse not the same object that collides? 
    // in that case you would rather simply do
    //mouse = other.gameObject;
    mouse = GameObject.Find("mouse");

    // teleport to currently next target
    mouse.transform.position = SPS[index].position;

    Debug.Log("Teleported to track #" + SPS[index], SPS[index]);
    
    // Update to the next index, wrapping around at the end of array
    index = (index + 1) % SPS.Length;
}

相关问题