Home > Software engineering >  C# Instantiate Vector3 Problems
C# Instantiate Vector3 Problems

Time:02-02

Instantiate(o, new Vector3(LocateX, LocateY, 0), transform.rotation); In this code Visual Studio 2022 keep telling me there is error with LocateX and LocateY... Please help me using Unity error code : 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;
        float LocateY;
        int ix = 1;
        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)
                {
                    LocateX = -3;
                    ix = ix   3;
                } else if (ix   1 == i)
                {
                    LocateX = 0;
                    ix = ix   3;
                } else if (ix   2 == i)
                {
                    LocateX = 3;
                    ix = ix   3;
                }

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

I tried change LocateX and LocateY into int and I changed float again. I have no idea how to solve it.

CodePudding user response:

Initialization is required before using local variables.

    float LocateX = 0;
    float LocateY = 0;

CodePudding user response:

You can try using modulo arithemtics here: for

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

we can put

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

And get

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;
    }
  }
}
  • Related