skip to Main Content

I’m a beginner of learning programming
Instantiate(o, new Vector3(LocateX, LocateY, 0), transform.rotation);
In this code Visual Studio 2022 keeps telling me there is an error with LocateX and LocateY…
Please help me
using Unity
error code : CS0165

FixedCode

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 ++;
            }
        }
    }
}

Problem Solved!!

I know my code is not clean at all so thank you for helping noob everyone!

2

Answers


  1. Initialization is required before using local variables.

        float LocateX = 0;
        float LocateY = 0;
    
    Login or Signup to reply.
  2. 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;
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search