- Home /
Other
How to correctly add audio to rolling ball
Hi,
i've been messing with this for a week and have had no success. I want to add sound to the ball, and when it picks up speed for the audio to speed up. I know i would use Pitch for this, but i'm not sure how to correctly incorporate it into my script. I tried adding a second audio source, but to no avail. I was able to get the "clank" (_audio1 in script) sound when the object hits walls, but that's a bout it. Any help would be greatly appreciated as there's very little material on how to do this. Below is script in C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
AudioSource _audio;
[SerializeField]
AudioClip _clip;
AudioSource _audio2;
[SerializeField]
AudioClip _clip2;
[SerializeField]
Rigidbody _rigidBody;
float _nominalSpeed;
private void Start()
{
_audio = GetComponent<AudioSource>();
_audio2 = GetComponent<AudioSource>();
_rigidBody = GetComponent<Rigidbody>();
//_Play = true;
}
private void Update()
{
_nominalSpeed = _rigidBody.velocity.magnitude;
//_audio.pitch = _rigidBody.velocity.magnitude / _nominalSpeed;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ground" && _nominalSpeed >= 0.1)
_audio.Play();
_audio2.Play();
else if (collision.gameObject.tag == "Ground" && _nominalSpeed < 0.1)
_audio.Pause();
}
}
I can't seem to get the code to fit, I tried code tags.
Answer by Vollmondum · Mar 26, 2019 at 06:07 AM
To start with, don't you EVER use _ sign.
Then, [SerializeField] is something you don't just stick here and there. Read about when and why.
Read what's public and private (and protected and static) and why and when it's used.
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class myBalls: MonoBehaviour { public AudioSource ballsAudioSource; public AudioClip ballsSound; public float defaultSpeed; public float currentSpeed; public float defaultPich; void Start() { ballsAudioSource = GetComponent<AudioSource>(); } void Update() { ballsAudioSource.pitch = defaultPitch * (currentSpeed / defaultSpeed); } void OnCollisionEnter(Collision col) { if(col.gameObject.tag == "Ground" && GetComponent<RigidBody>().velocity > 0) { if(!ballsAudioSource.isPlaying()) { ballsAudioSource.Play(); } } else { ballsAudioSource.Stop(); } } }
Not sure if it'll compile, modify whatever lines as needed. Gave you main logic.
lol why can't I EVER use this? In a class I was taking they said it was good practice to use. Oh well, I figured it out, but thanks for the comment.