I need some help in my Rhythm game

I want to make a rhythm game in unity and I wrote a script to spawn note base on the music beat but the problem is script spawn object when the music hit the beat but I want to spawn all notes when the game start.

Script Given Below:

using UnityEngine;

public class BeatDetector : MonoBehaviour
{

// MY SCRIPT CREATED////////////
// MY SCRIPT CREATED////////////
// MY SCRIPT CREATED////////////
// MY SCRIPT CREATED////////////
// MY SCRIPT CREATED////////////

public AudioSource audioSource;
public GameObject objectToSpawn;
public float spawnInterval = 0.5f; // Time between spawns
public float beatThreshold = 0.1f; // Minimum amplitude to consider a beat

private float[] samples = new float[512];
private float lastSpawnTime = 0f;

public Vector3 spawnPosition;
public float bpm;

private void Awake()
{
    bpm = bpm / 60f;
}

void Update()
{
    AnalyzeAudio();
    DetectBeat();
}

void AnalyzeAudio()
{
    // Check if audioSource is playing
    if (!audioSource.isPlaying)
        return;

    // Get audio data
    audioSource.GetOutputData(samples, 0);
}

void DetectBeat()
{
    float averageAmplitude = 0f;
    spawnPosition.z += bpm * Time.deltaTime;
    // Calculate average amplitude from the audio samples
    for (int i = 0; i < samples.Length; i++)
    {
        averageAmplitude += Mathf.Abs(samples[i]);
    }

    averageAmplitude /= samples.Length;

    // Debugging output to monitor amplitude values
    Debug.Log("Average Amplitude: " + averageAmplitude);

    // Check if average amplitude exceeds the beat threshold
    if (averageAmplitude > beatThreshold && Time.time - lastSpawnTime > spawnInterval)
    {
        SpawnObject();
        lastSpawnTime = Time.time;
    }
}

void SpawnObject()
{
    Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);
    Debug.Log("Object spawned at: " + transform.position);
}

}

Looking at that script, the beat is analyzed after (or while) the song is played. Therefore, until the song plays, it’s not aware of what the beat is.

To my mind, the only way to do that is to play the song in the background, with no audio, and once the beat is determined, it can spawn the objects. Instantiating is slow, so I would also recommend that the notes are already existing in the scene, but inactive, and rather than spawn, activate them.

But i want to get the notes automatically so i can use any kind of music but if i use this method then i need to play every songs and need to store all notes data. Which time consuming. :roll_eyes:

Okay, so? Audiosurf doesn’t do it on the fly, it precalculates everything too. So do all rhythm games. They load up the file, scan it, then handle the note generation from there. The only ones that don’t are ones where the users generate their own steps by hand.

Yaah, to do this the file needs to be opened and scanned. It probably wouldn’t have to play it in realtime, it depends on the algorithm/library that is doing the analysis.