how to access a variable from another method

I know that there are already 2 threads like this but both recommend making it a global variables but I cant because I need a 2d array that uses 2 other variables like this

public int y;
    public int x;
int[,] map = new int[y, x];
start() {
#blah blah blah
    }
update() {
#blah blah blah
    }

but this gives the errors
a field initializer cannot reference the field. method, or property ‘spawner.y’
a field initializer cannot reference the field. method, or property ‘spawner.x’
so unless you know how to fix this I need to access a variable from another method

First, when posting code, be sure to use the code tags feature the forum provides. This will format your code and make it easier for the rest of us to read.

Next, you should also post actual code that you’ve having a problem with, not some generic placeholder that doesn’t actually represent your problem. Here you’ve mentioned not being able to access spawner.x/y, but haven’t shown us how you’re actually trying to use that. We can’t give useful advice if we don’t know what your actual problem is.

There shouldn’t be any problem accessing properties of a class from inside any of its methods. It’s possible you’re declaring local variables inside of one of your methods, in which case, they are inaccessible from outside that method by design. This is due to how scope and memory work, and trust me, you wouldn’t want it to work any other way. But again, because you haven’t shared actual code, I can only guess here instead of providing information more specific to you.

but I’m giving you the part of the code that’s giving me the error the array that cant access variables x/y is right next to them would you rather I give you the entire code?

You cannot reference fields until after they’ve been initialized.

public int x;
public int y;

int[,] map = new int[y, x]; //Will not work. y and x haven't been initialized yet.

You must do so in a method instead. For MonoBehaviours, the Awake method is likely what you want to use:

public int x;
public int y;

int[,] map;

void Awake() {
  map = new int[y, x];
}
1 Like

thank you I realized why it wasn’t working but I couldn’t figure out how to do it I thought I could define the variable in start but then I realized update couldn’t access it this works a lot better thank you