Soundsource Engine Pitch and Speed Text (Please Give an Answer This Time)

I want to connect my car’s engine sound (which is an audio source) to my script so the faster the car goes the higher pitched the sound will be. Also the text that prints the speed of the car onto the canvas is real buggy, sometimes when standing still it glitches between 0-12 (also it looks like this: 2.3473643m/s not like this: 23m/s) Can someone help me with it?

Also I dont know why but why does this community already ignores me? I posted this same question days ago and people answered all questions above and bellow! People ignore me because im a new member or because i cant script or whats going on, seriously?

The community does neither ignore new members nor people who are new to scripting. Everyone is welcome.

Posts are likely to get ignored when noone has a helpful answer to the question at hand (which is probably not the case here) or when the post feels incomplete or kinda feels like it demands to get all the work done.

If we’re talking about this thread , there’s some sort of lack of information. It only shows what you’re trying to achieve and the current outcomes. You should include the scripts that produce the unexpected results & behaviour.

It has no unexpected behaviour, only the text that shows the speed should be that accurate. Its enough if its shows something like 100km/h and not 100.3453km/h. And what about the soundsource? How do i connect it to my script so the faster i go, the higher the pitch. I think its pretty clear what should be done, because a lot of talented people are part of this forum, not monkeys. But whatever, here the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;

public class CarSpeed : MonoBehaviour {

public Text SpeedText;
public Rigidbody _rb;

void Start()
{
_rb = GetComponent();
}

void Update()
{
SpeedText.text = _rb.velocity.magnitude.ToString() + “m/s”;
}
}

Hope this helped (but ithink it would be the same without this)
Also i dont think that out of the 100 trillion (dont take it serious) users at least 1 or 2 cant give a simple answer…

The magnitude property returns a single precision floating point number (float), which will not be truncated by default when you call ToString on it. If you only need the integer part of it, you can cast it to an integer before calling ToString. This will effectively cut off the decimals. Another alternative is using an overload of the ToString function, that takes in the number of decimals that should be included in the stringified version.
That overload used to take a simple string with the format of “FX” where X is the number of decimals.

Add a field of type AudioSource that’s exposed to the inspector, drag and dop the source you want to access and change the pitch programmatically. That’s something you have to code. I cannot tell you the best speed-to-pitch-mapping (a simple formular is often enough), but that’s something you have to tweak on your own anyway.
That is, take you speed value, pass it to your pitching formula (whatever fits your needs) and assign the result as a pitch value.

Well, that’s exactly the attitude many community members don’t like. Don’t get me wrong, but this reads like “hey, i need this, just do it for me”. There are tons of gifted and friendly people here. They like - or even love - to help, but this isn’t a place to simply dispatch your work - it’s a place to help each other, which includes your own participation and effort as well.

1 Like

Welp i still dont know what to do with the script but at least i got some idea. I dont know how to “drag and drop” the source into the script itself, i dont know really anything about scripting. Nothing. 0%. I cant find anything online too, because everyone gives a different answer that doesnt work at all or its just wont work with the game im making. So, what do i use in my script to make it work? Its enough if you write something like: “Oh you can use GetComponent(); and it will do this and then connect this to it and it does that”

If you’re completely new, I highly recommend to read through the beginner tutorials. It makes everything easier.

There are vaious ways to access the components, and yes, one of them is

GetComponent<ComponentType>();

or in general one of these

anyGameObject.GetComponent<ComponentType>();
anyComponent.GetComponent<ComponentType>();

The difference will be clear once you read about instance methods in object oriented programming. It’ll be difficult and highly unlikely that you make a lot of progress if you do not take the time to learn the basics of C#.

Drag&drop works when you expose your fields to the inspector, for instance:

public class ExampleScript : MonoBehaviour
{
    // I will keep it simple here, let's just put it as public
    public int integerValue;
    public float floatingPointValue;

    public Transform callMeWhateverYouWant;
}

If the snippet resides in a file named ExampleScript.cs, you’ll be able to attach it to any GameObject and it’ll show three fields in the inspector: two input fields for numerical values (integer and float respectively) and one field that accepts a GameObject with a Transform component (every GO has a transform, so you could drag&drop anything you like).

Applying this idea to your script, you could add

public AudioSource engineSoundSource;

and it should now show a field to drag&drop an object that’s got an AudioSource component, e.g. your car.

Now you’ll be able to work with engineSoundSource in your script, as this is a declared variable.

With regards to your question, take a look at the AudioSource.pitch example. You should be able to test this as is - you only need to copy&paste the script into a .cs file that’s got the same name as the class (which is ‘Try’) and drag&drop a sound-file into the AudioSource component.

If this seems already a bit too much, I can only recommend to spend a few days or weeks on learning the fundamentals of Unity and C#.

Okay thanks! I will try it out right now and see if it works!

Okay it cannot convert float into int somehow
It looks something like this so far:
public class CarSpeed : MonoBehaviour {

public Text SpeedText;
public Rigidbody _rb;
public int speedNormal; ← new stuff

void Start()
{
_rb = GetComponent();
speedNormal = _rb.velocity.magnitude; ← this is new
}

void Update()
{
speedNormal = _rb.velocity.magnitude.ToString(); ← and this is new too
SpeedText.text = speedNormal + “m/s”;
}
}

You changed the varibale type, but you did not cast / convert it.

Let’s retain the decimals in case you need to get the value from another script, too.
Instead, cast it just in place.

The script can be as simple as follows:

using UnityEngine;
using UnityEngine.UI;

public class CarSpeed : MonoBehaviour
{
    public Text _speedText;
    public Rigidbody _rb;

    private float _speed;

    // if you drag&drop the rigidbody in the inspector, you could even remove this Awake function
    private void Awake()
    {
        _rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        _speed = (int)_rb.velocity.magnitude;
        _speedText.text = _speed + "m/s";
    }
}

Okay i fixed it, but now connecting the audiosource to it and then multiplying it doesnt work. It cant convert from double to float, and the two things are almost the same.

public class CarSpeed : MonoBehaviour {

public Text SpeedText;
public Rigidbody _rb;
public float speedNormal;
public int enginePitch;
AudioSource carSound;

void Start()
{
_rb = GetComponent();
speedNormal = _rb.velocity.magnitude;
carSound = GetComponent();
}

void Update()
{
speedNormal = (int)_rb.velocity.magnitude;
SpeedText.text = speedNormal + “m/s”;
}
}

If you were trying to use floating point numbers, you have to add the a suffix (f or F) for single precision floating point numbers (float), otherwise the number defaults to a double precision floating point number (double).
Single precision can be implicitly converted to double precision. In order to convert it the other way around, you’ll need an explicit cast (as shown with the integer). But you won’t need doubles in this case, just use floats.

All you need to do now is:

carSound.pitch = /* add your speed-dependent calculation here*/

As mentioned in a previous post, you have to figure out the formula by yourself. I cannot help with that, as this depends on your audio samples and your desired final result.

Uuuuh somehow like this? carSound = ('f) speedNormal;
Because that doesnt work, and i still dont know how to do this converting stuff

No, but that’s something you should have found easily using a search engine.

 float abc = 5.0f;

The ‘f’ suffix tells the compiler we’re dealing with a float literal.

Also, you cannot just assign a float to ‘carSound’, you wanna set the pitch, as shown in previous examples.

Few examples would be

carSound.pitch = speedNormal; // probably not a good idea
carSound.pitch = speedNormal * 0.1f; // maybe this
carSound.pitch = speedNormal * 0.2f; // maybe that

// from the samples above, you notice that that there's one value that might need some tweaking
// so we can turn it into another vaiable

// at the top of your script, you can add this one,
// so you'll be able to modify the value in the inspector
public float pitchFactor;

// in your update, you could then do
carSound.pitch = speedNormal * pitchFactor;

The right-hand side can be anything that evaluates to a float-value. It can be a hard-coded literal, a variable, a simple math function, a complex math-function … That’s really up to you. As mentioned, I cannot do that for you.

Ooooh i get it now! Okay imma try it out and see if i can figure it out!

Theres no audiosource connected to my car it says. Hah! Real funny, its literally there! Unity is blind or something. Also when testing, it deletes the soundsource from the “car sound” slot!

Most-likely not Unity’s fault, but a wrong setup.

Perhaps it is not on the same object, but on a child object or it is attached on a completely different gameobject. When you use GetComponent without specifying any gameObject, it’ll attempt to get the component from the object that your script is attached to (the script which which makes use of GetComponent).

Or you’ve accidently attached the script to a second object, which then throws the error while the other one runs fine.

Noone can tell you the exact reason if you do not add more information.

I think it’s also time to visit the learning section.

Weird because the script is only connected to the car, and the soundsource is there too. I even removed the component and then added it back ,but i got the same result again.

Okay i fixed it! Thanks for all the help! :slight_smile:

1 Like