Coin generator code optimization

using System.Collections;
using UnityEngine;

public class CurrencyGeneration : MonoBehaviour
{
    public GameObject currency;
    float xRange = 2f;
    float yRange = 2.5f;
    int currencyAmount = 10;

    void Start()
    {
        StartCoroutine(GenerateCoin());
    }
    IEnumerator GenerateCoin() {
        for (int i = 0; i < currencyAmount; i++) {

            float timeBeforeNext = Random.Range(.1f,.2f);

            Vector3 currencyPosition = transform.position;
            GameObject createdCoin = GameObject.Instantiate(currency, currencyPosition, Quaternion.identity);

            Vector3 coinThrow = new Vector3(Random.Range(-xRange, xRange), Random.Range(0, yRange), 0);
            createdCoin.GetComponent<Rigidbody2D>().velocity = coinThrow;

            yield return new WaitForSeconds(timeBeforeNext);
        }
    }
}

I’m looking for any feedback about this code’s efficiency. It works exactly like I want, but is it well-optimized?

I mean you’re executing the code every 1/10th to 1/5th of a second. It could be a hundred times more complex and you’d never notice it.

So is it better to use fixed update for this one

Worse. FixedUpdate is only really useful if you need to execute code constantly.

So what would give me more performance. I’m new to unity, so maybe it is some useful method I can read about

Nothing. It’s fine as it is. If you’re having performance problems it isn’t with that code.

Thanks for your reply, I was just wondering about this exact part optimization. I worry about it so much

Yeah, that kind of worry is normal when you’re just getting started, but the best way isn’t to guess. Unity has a tool to help you find sections of your project that aren’t performing well.

2 Likes

Huge thanks! Didn’t know about this tool