Converting one range of numbers to another range is very common. In unity, you often want to convert one number range to another number range. Like I want to map 1 to 100 numbers into 1 to 1000. Let's see a practical example, I want to enable the user to set object Transparency using a text-field where the user can enter transparency value. Like from 0 to 100 he can assign an alpha/Transparency/Opacity value but behind the scenes, the alpha value can be from 0 to 1. Then, what should happen? Here range conversion will be required.
(You can also watch how to set object transparency using C# code in blow video.)
Now to handle this thing we have to remap one range of numbers to another range. Therefore this handy function I have found in this > thread and sharing with you some naming improvements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class ConvertOneRangeToAnother : MonoBehaviour | |
{ | |
[Header("Input Value to convert")] | |
public float inputValue = 10; | |
[Header("Input Range")] | |
public float StartInputRange = 0; | |
public float EndInputRange = 100; | |
[Header("Output Range")] | |
public float StartOutputRange = 0; | |
public float EndOutputRange = 1; | |
void Update() | |
{ | |
Debug.Log(remap(inputValue, StartInputRange, EndInputRange, StartOutputRange, EndOutputRange)); | |
} | |
/// <summary> | |
/// convert one range to another range | |
/// </summary> | |
/// <param name="valueToConvert">input value to convert</param> | |
/// <param name="StartInputRange"></param> | |
/// <param name="EndInputRange"></param> | |
/// <param name="StartOutputRange"></param> | |
/// <param name="EndOuputRange"></param> | |
/// <returns></returns> | |
public static float remap(float valueToConvert, float StartInputRange, float EndInputRange, float StartOutputRange, float EndOuputRange) | |
{ | |
return StartOutputRange + (valueToConvert - StartInputRange) * (EndOuputRange - StartOutputRange) / (EndInputRange - StartInputRange); | |
} | |
} |
you can call Remap(5, 1, 10, -50, 100) with these parameters and it will return the converted number. Here is the function calling explanation:
- First Parameter represent the actual number we want to convert
- 2nd n 3rd Parameter: The actual range start/stop
- 3rd n 4th Parameter: The convert range start/stop
0 Comments