Convert one range of Number to another range in C# Unity3d

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.

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:

  1. First Parameter represent the actual number we want to convert
  2. 2nd n 3rd Parameter: The actual range start/stop
  3. 3rd n 4th Parameter: The convert range start/stop

Post a Comment

0 Comments