I am playing around with Unity and experimenting a bit; I have this code that I am attempting to have to instantiate a cube with a sine.wav file. I want to avoid using the inspector if possible and have things instantiate in run time; here is the code I have; when I run it, everything seems to work as expected, except I don’t hear any audio.
public class Main : MonoBehaviour
{
void Start()
{
// Spawn cube and add audio listener
CubeSpawner spawner = gameObject.AddComponent<CubeSpawner>();
spawner.SpawnCube(new Vector3(10, 10, 10), new Vector3(2, 2, 3));
// Create a new game object and add an audio listener component to it
GameObject audioListenerObj = new GameObject("Audio Listener");
audioListenerObj.transform.position = Vector3.zero;
audioListenerObj.AddComponent<AudioListener>();
}
}
public class CubeSpawner : MonoBehaviour
{
public GameObject cubePrefab; // the prefab for the cube we want to spawn
public void SpawnCube(Vector3 position, Vector3 size)
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); // create a cube object
cube.transform.position = position; // set the position of the cube to the specified position
cube.transform.localScale = size; // set the scale of the cube to the specified size
cube.AddComponent<Cube>(); // add the Cube script to the cube object
// add Rigidbody component to the cube
Rigidbody rb = cube.AddComponent<Rigidbody>();
rb.mass = 1;
rb.useGravity = true;
// add MeshCollider component to the cube
MeshCollider meshCollider = cube.AddComponent<MeshCollider>();
meshCollider.convex = true;
}
}
[RequireComponent(typeof(AudioSource))]
public class Cube : MonoBehaviour
{
public float amplitude = 0.5f; // amplitude of the sine wave
public float frequency = 440f; // frequency of the sine wave
public float speed = 1f; // speed of the sine wave
private Vector3 startPosition; // starting position of the cube
private AudioSource audioSource; // audio source component attached to the cube
void Start()
{
startPosition = transform.position; // store the starting position of the cube
audioSource = GetComponent<AudioSource>(); // get the audio source component attached to the cube
audioSource.loop = true; // enable looping for the audio source
}
void Update()
{
// calculate the sine wave value based on time
float time = Time.time * speed;
float sineValue = amplitude * Mathf.Sin(2 * Mathf.PI * frequency * time);
// apply the sine wave to the Y position of the cube
transform.position = startPosition + new Vector3(0f, sineValue, 0f);
// set the audio source pitch to the sine wave value
float pitch = Mathf.InverseLerp(-1f, 1f, sineValue);
audioSource.pitch = Mathf.Lerp(0.5f, 2f, pitch);
// play the audio source
if (!audioSource.isPlaying) {
audioSource.Play();
}
}
}
Any idea about what I am doing wrong? Thanks for any feedback.