Invert Audio Volume

Hello UA! How can I invert the volume value of an Audiosource in C# so that the value 0.0 is full volume and 1.0 is no volume? In my game I want to start playing a heartbeat sound when my “currentHealth” float is 40, and increase the volume as “currentHealth” gets lower.

        if (curHealth > 46) { heartBeatSource.volume = 0; }
		if (curHealth <= 45) { heartBeatSource.volume = .1f; }
		if (curHealth <= 40) { heartBeatSource.volume = .2f; }
		if (curHealth <= 35) { heartBeatSource.volume = .3f; }
		if (curHealth <= 30) { heartBeatSource.volume = .4f; }
		if (curHealth <= 25) { heartBeatSource.volume = .5f; }
		if (curHealth <= 20) { heartBeatSource.volume = .6f; }
		if (curHealth <= 15) { heartBeatSource.volume = .7f; }
		if (curHealth <= 10) { heartBeatSource.volume = .8f; }
		if (curHealth <= 5) { heartBeatSource.volume = .9f; }

That works, but it’s not a very efficient way of doing it. Thanks all :slight_smile:

@hellopeople0004

Try getting the percentage of health, subtracting that from 100, then setting the volume to equal that result.

Something like this; I haven’t tested it out or anything though

float percentHealth = currentHealth/maxHealth;     //in your case maxHealth is 46
float percentVolume = 1 - percentHealth;
heartbeatsource.volume = percentVolume;