More optimized way of writing this code

Hi there,

So I wrote this code to spawn a coin in x,y,z positions but I was wondering if there is a better way to go about this rather than creating similar code 3 times:

        // X Coins
        float xOffset = 0f;
        for(int x=0; x < coinAmount.x;x++)
        {
            Instantiate(coin, transform.position + new Vector3(xOffset, 0f, 0f), Quaternion.identity);
            xOffset = xOffset + offsetAmount.x;
        }
        // Y Coins
        float yOffset = 0f;
        for (int y = 0; y < coinAmount.y; y++)
        {
            Instantiate(coin, transform.position + new Vector3(0f, yOffset, 0f), Quaternion.identity);
            yOffset = yOffset + offsetAmount.y;
        }
        // Z Coins
        float zOffset = 0f;
        for (int z = 0; z < coinAmount.z; z++)
        {
            Instantiate(coin, transform.position + new Vector3(0f, 0f, zOffset), Quaternion.identity);
            zOffset = zOffset + offsetAmount.z;
        }

As you can I see all three loops are pretty much the same except change axis.

If you could suggest a way I could make this more efficient I’d appreciate it,
Thanks :slight_smile:

You could do this:

private void SpawnCoins(int cointAmount, float offsetAmount,  Vector3 direction) {
  float offset = 0f;
  for (int c = 0; c < coinAmount; c++) {
    Instantiate(coin, transform.position + direction * offset, Quaternion.identity);
    offset += offsetAmount);
  }
}

void SpawnAllTheCoins() {
  SpawnCoins(coinAmount.x, offsetAmount.x, Vector3.right);
  SpawnCoins(coinAmount.y, offsetAmount.y, Vector3.up);
  SpawnCoins(coinAmount.z, offsetAmount.z, Vector3.forward);
}

Note: In this method and your original method, you’re spawning three coins all in the same space at transform.position because your offsets start at 0, not sure you’re aware of that. :wink:

2 Likes

This is how I would do it. Reduce it to a single loop. One rarely used method of accessing Vector3 values is to use their indices. This allows for this kind of logic.

Vector3 offset = Vector3.zero;
float totalCoins = coinAmount.x + coinAmount.y + coinAmount.z;
int currentAxis = 0;
int currentCoin = 0;

for (var i = 0; i < totalCoins; i++)
{
    offset[currentAxis] += offsetAmount[currentAxis];
    Instantiate(coin, transform.position + offset, Quaternion.identity);
    currentCoin++;
    if (currentCoin > coinAmount[currentAxis])
    {
        currentAxis++;
        if (currentAxis > 2)
            break;
        currentCoin = 0;
        offset = Vector3.zero;
    }
}
1 Like

Thank you very much, never thought of doing it like that! (forgot to post a reply :p)