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);
}
}