unity3d C#示例化Vector3问题

wecizke3  于 2023-02-05  发布在  C#
关注(0)|答案(2)|浏览(221)

我是一个初学者学习编程示例化(o,新向量3(LocateX,LocateY,0),变换。旋转);在这段代码中,Visual Studio 2022一直告诉我LocateX和LocateY有错误...请帮助我使用Unity错误代码:CS0165

using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class OXScript : MonoBehaviour
{
    private int clickNumber;
    public GameObject o;
    public int spotNumber;

    // Start is called before the first frame update
    void Start()
    {
        clickNumber= 0;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void SpawnO()
    {
        //  1,   2,  3, y = 3
        //  4,   5,  6, y = 0
        //  7,   8,  9, y = -3
        // x=-3 x=0 x=3

        float LocateX = 0;
        float LocateY = 0;
        int ix = 0;
        for(int i=1; i<10; i++)
        {
            if (clickNumber == 0 && spotNumber == i)
            {
                // y
                if(1 <= i && i <= 3 )
                {
                    LocateY = 3;
                } else if(4 <= i && i <= 6)
                {
                    LocateY = 0;
                } else if (7 <= i && i <= 9)
                {
                    LocateY = -3;
                }
                //x
                if (ix == (i - 1) % 3)
                {
                    LocateX = -3;
                } else if (ix + 1 == (i - 1) % 3)
                {
                    LocateX = 0;
                } else if (ix + 2 == (i - 1) % 3)
                {
                    LocateX = 3;
                }

                Instantiate(o, new Vector3(LocateX, LocateY, 0), transform.rotation);
                spotNumber ++;
                clickNumber ++;
            }
        }
    }
}

问题解决!!
我知道我的代码一点也不干净,所以谢谢大家!

cwtwac6a

cwtwac6a1#

在使用局部变量之前需要初始化。

float LocateX = 0;
    float LocateY = 0;
bvjxkvbb

bvjxkvbb2#

您可以尝试使用 *modulo arithematics *:为

1,        2,       3    y = 3
    4,        5,       6    y = 0
    7,        8,       9    y = -3
    x = -3    x = 0    x = 3

我们可以把

x = ((i - 1) % 3 - 1) * 3
   y = (1 - (i - 1) / 3) * 3

并得到

public void SpawnO() {
  for (int i = 1; i < 10; ++i) {
    if (clickNumber == 0 && spotNumber == i) {
      int LocateX = ((i - 1) % 3 - 1) * 3
      int LocateY = (1 - (i - 1) / 3) * 3;

      Instantiate(o, new Vector3(LocateX, LocateY, 0), transform.rotation);

      spotNumber += 1;
    }
  }
}

相关问题