I'm trying to put some code into methods to simplify/optimize my code. The game I'm making is a falling-sand type game and right now the script for each particle goes through the entire grid looking for that type of material and executing its code whenever it shows up. I'm trying to make it so that it only scans the grid one time, and runs the appropriate material's script at each location. Up until now all of my methods have been working, but when I try to do it inside a For Loop, it stops working. Effectively what I'm doing is taking this, which works:
private void ParticleBehavior()
{
for (int x = 0; x < gridXY.x; x )
{
for (int y = 0; y < gridXY.y; y )
{
if (tilemapCurrent.GetTile(new Vector3Int(x, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x, y - 1, 0)) == null)
{ //if tile below is empty, move there
tilemapNext.SetTile(new Vector3Int(x, y - 1, 0), sand);
}
//For simplicity sake I removed a couple dozens of lines of code here because they're not pertinent to the question
}
}
}
and turning it into this, which doesn't: (Edit: By 'doesn't work' I mean none of the contained code executes, so no tiles in 'tilemapNext' get updated to sand tiles)
private void ParticleBehavior()
{
for (int x = 0; x < gridXY.x; x )
{
for (int y = 0; y < gridXY.y; y )
{
SandBehavior();
//If this worked this is also where I'd put every other particle behavior method
}
}
}
private void SandBehavior()
{
if (tilemapCurrent.GetTile(new Vector3Int(x, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x, y - 1, 0)) == null)
{ //if tile below is empty, move there
tilemapNext.SetTile(new Vector3Int(x, y - 1, 0), sand);
}
//For simplicity sake I removed a couple dozens of lines of code here because they're not pertinent to the question
}
Thank you!
CodePudding user response:
You need to pass the values for x and y into the methods:
...
for (int y = 0; y < gridXY.y; y )
{
SandBehavior(x, y);
}
...
private void SandBehavior(int x, int y)
{
if (tilemapCurrent.GetTile(new Vector3Int(x, y - 1, 0)) == null && tilemapNext.GetTile(new Vector3Int(x, y - 1, 0)) == null)
{ //if tile below is empty, move there
tilemapNext.SetTile(new Vector3Int(x, y - 1, 0), sand);
}
}
You'll need to pass all fields/properties used within your method, unless they are static or class member fields/properties. For example, sand will need to be passed in too, unless its static or declared at class level.
CodePudding user response:
Are you sure that the variables you are using e.g tilemapCurrent or x, y are accessible through your new Method also? maybe it is better to get all variables used in SandBehavior() method taken as parameters like this:
private void SandBehavior(tilemapCurrent, x, y, tilemapNext)
{
if (tilemapCurrent.GetTile(new Vector3Int(x, y - 1, 0)) == null &&
tilemapNext.GetTile(new Vector3Int(x, y - 1, 0)) == null)
{
tilemapNext.SetTile(new Vector3Int(x, y - 1, 0), sand);
}
}
then pass them wherever you are using it.
