Sign in to follow this  

Unity Website for code library?

This topic is 1940 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've developed a class called "Range" which keeps track of a number between a min and max number. It's useful for keeping track of any data which could be represented by a progress bar (hitpoints, mana, cooldown time, etc) and generating a random number within the range. I think other people would find it useful within their projects, so I'd like to share it. Is there a section on this site for freely sharing reusable code? In case there isn't, I'm copy/pasting it below. You're free to use it in any way with no strings attached and no guarantee of fitness/correctness.

Note: My code sample is relatively trivial and generic enough to be usable in any game/app. It's 95% tested, but not very rigorously as it should be.

[b]Range.cs - C# XNA Version:[/b]
[CODE]
using System;
using Microsoft.Xna.Framework;
namespace EricsLib
{
/// <summary>
/// The range class gives you a number which is between a min and max number.
/// Usages: -Keeping track of hitpoints or similar metrics
/// -keeping track of ability cool down timers
/// -Generating random numbers within a range
/// -Storing direction angles or other circular data (use looping values)
/// </summary>
public class Range
{
float m_max, m_min; //the thresholds for the meter value
float m_regen; //how many points you want to regenerate/degenerate every second
float m_current; //the current value of the meter
bool m_loopValues; //if this is 'true', then the current value will loop between min and max values instead of being capped.
public Range()
{
m_max = 100;
m_min = 0;
m_current = 100;
m_regen = 0;
m_loopValues = false;
}
/// <summary>
/// Creates a range with the current value at max value and min at zero
/// </summary>
/// <param name="max">the highest range value allowed</param>
public Range(float max)
{
m_max = max;
m_current = max;
m_min = 0.0f;
m_loopValues = false;
}
/// <summary>
/// creates a range value with the current value defaulted to the max value
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
public Range(float min, float max)
{
m_max = max;
m_min = min;
m_current = max;
m_loopValues = false;
}
/// <summary>
/// Creates a range
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current range value</param>
public Range(float min, float max, float current)
{
m_max = max;
m_min = min;
m_current = current;
m_loopValues = false;
}
/// <summary>
/// creates a range value with regeneration/decay value set so the current value increases/decreases over time
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current value in range</param>
/// <param name="regen">the change in current value over time</param>
public Range(float min, float max, float current, float regen)
{
m_max = max;
m_min = min;
m_current = current;
m_regen = regen;
m_loopValues = false;
}
public Range(Range Copy)
{
if (Copy == null)
return;
m_max = Copy.m_max;
m_min = Copy.m_min;
m_current = Copy.m_current;
m_regen = Copy.m_regen;
m_loopValues = Copy.m_loopValues;
}
/// <summary>
/// The current value will always be between min and max values
/// </summary>
public float Current
{
get
{
return m_current; //E: I'm assuming this gets truncated.
}
set
{
//do some quick bounds checking
if (value > m_max) //value is greater than specified max value
{
if (m_loopValues)
{
//the remaining looped value should be seamlessly added to the minimum value if it overflows the max
m_current = m_min + (value % m_max); //tested
}
else
{
m_current = m_max;
}
}
else if (value < m_min) //value is less than specified minimum value
{
if (m_loopValues)
{
m_current = m_min + (value % (m_max - m_min)); //tested
}
else
{
m_current = m_min;
}
}
else
m_current = value;
}
}
/// <summary>
/// Sets the current value to a random number between the min and max range values
/// </summary>
/// <param name="SetCurrent">Flag on whether you want to set the current value to the randomly generated number</param>
/// <returns>the value of current</returns>
public float Random(bool SetCurrent)
{
double d = Calc.random.NextDouble();
float diff = m_max - m_min;
diff *= (float)d;
if (SetCurrent == true)
{
m_current = m_max - diff;
}
return m_max - diff;
}
/// <summary>
/// Returns a random float which lies between min and max value of the range.
/// </summary>
/// <returns></returns>
public float Random()
{
return Random(false);
}
public float Max
{
get
{
return m_max;
}
set
{
m_max = value;
}
}
public float Min
{
get
{
return m_min;
}
set
{
m_min = value;
}
}
public float Half
{
get
{
return (m_min + m_max) / 2.0f;
}
}
/// <summary>
/// Per second regeneration/decay value for the current value of the meter
/// </summary>
public float RegenRate
{
get
{
return m_regen;
}
set
{
m_regen = value;
}
}
public void Update(GameTime gameTime)
{
//are we regenerating/decaying over time?
if (m_regen != 0)
{
Current += m_regen * (gameTime.ElapsedGameTime.Milliseconds);
}
}
public void SetToMax()
{
m_current = m_max;
}
public void SetToMin()
{
m_current = m_min;
}
public bool IsEmpty()
{
return (m_current <= m_min);
}
/// <summary>
/// Set/Get the current value as a percentage of the min and max values
/// </summary>
public float Percent
{
get
{
return ((m_current - m_min) / (m_max - m_min)) * 100;
}
set
{
m_current = m_min + ((value / 100) * (m_max - m_min));
}
}
/// <summary>
/// if this is 'true', then the current value will loop between min and max values instead of being capped.
/// Default: false
/// </summary>
public bool LoopValues
{
get
{
return m_loopValues;
}
set
{
m_loopValues = value;
}
}
/// <summary>
/// Tells you if the current range value is at the maximum value
/// </summary>
/// <returns></returns>
public bool IsMax()
{
return m_current == m_max;
}
/// <summary>
/// Tells you if the current range value is at the minimum value
/// </summary>
/// <returns></returns>
public bool IsMin()
{
return m_current == m_min;
}
}
}
[/CODE]

[b]Range.cs - C# Unity3D version:[/b]
[CODE]
using System;
using UnityEngine;
namespace EricsLib
{
/// <summary>
/// The range class gives you a number which is between a min and max number.
/// Usages: -Keeping track of hitpoints or similar metrics
/// -keeping track of ability cool down timers
/// -Generating random numbers within a range
/// -Storing direction angles or other circular data (use looping values)
/// </summary>
public class Range
{
float m_max, m_min; //the thresholds for the meter value
float m_regen; //how many points you want to regenerate/degenerate every second
float m_current; //the current value of the meter
bool m_loopValues; //if this is 'true', then the current value will loop between min and max values instead of being capped.
public Range()
{
m_max = 100;
m_min = 0;
m_current = 100;
m_regen = 0;
m_loopValues = false;
}
/// <summary>
/// Creates a range with the current value at max value and min at zero
/// </summary>
/// <param name="max">the highest range value allowed</param>
public Range(float max)
{
m_max = max;
m_current = max;
m_min = 0.0f;
m_loopValues = false;
}
/// <summary>
/// creates a range value with the current value defaulted to the max value
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
public Range(float min, float max)
{
m_max = max;
m_min = min;
m_current = max;
m_loopValues = false;
}
/// <summary>
/// Creates a range
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current range value</param>
public Range(float min, float max, float current)
{
m_max = max;
m_min = min;
m_current = current;
m_loopValues = false;
}
/// <summary>
/// creates a range value with regeneration/decay value set so the current value increases/decreases over time
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current value in range</param>
/// <param name="regen">the change in current value over time</param>
public Range(float min, float max, float current, float regen)
{
m_max = max;
m_min = min;
m_current = current;
m_regen = regen;
m_loopValues = false;
}
public Range(Range Copy)
{
if (Copy == null)
return;
m_max = Copy.m_max;
m_min = Copy.m_min;
m_current = Copy.m_current;
m_regen = Copy.m_regen;
m_loopValues = Copy.m_loopValues;
}
/// <summary>
/// The current value will always be between min and max values
/// </summary>
public float Current
{
get
{
return m_current; //E: I'm assuming this gets truncated.
}
set
{
//do some quick bounds checking
if (value > m_max) //value is greater than specified max value
{
if (m_loopValues)
{
//the remaining looped value should be seamlessly added to the minimum value if it overflows the max
m_current = m_min + (value % m_max); //tested
}
else
{
m_current = m_max;
}
}
else if (value < m_min) //value is less than specified minimum value
{
if (m_loopValues)
{
m_current = m_min + (value % (m_max - m_min)); //tested
}
else
{
m_current = m_min;
}
}
else
m_current = value;
}
}
/// <summary>
/// Sets the current value to a random number between the min and max range values
/// </summary>
/// <param name="SetCurrent">Flag on whether you want to set the current value to the randomly generated number</param>
/// <returns>the value of current</returns>
public float Random(bool SetCurrent)
{
double d = Calc.random.NextDouble();
float diff = m_max - m_min;
diff *= (float)d;
if (SetCurrent == true)
{
m_current = m_max - diff;
}
return m_max - diff;
}
/// <summary>
/// Returns a random float which lies between min and max value of the range.
/// </summary>
/// <returns></returns>
public float Random()
{
return Random(false);
}
public float Max
{
get
{
return m_max;
}
set
{
m_max = value;
}
}
public float Min
{
get
{
return m_min;
}
set
{
m_min = value;
}
}
public float Half
{
get
{
return (m_min + m_max) / 2.0f;
}
}
/// <summary>
/// Per second regeneration/decay value for the current value of the meter
/// </summary>
public float RegenRate
{
get
{
return m_regen;
}
set
{
m_regen = value;
}
}
public void Update()
{
//are we regenerating/decaying over time?
if (m_regen != 0)
{
Current += m_regen * Time.deltaTime;
}
}
public void SetToMax()
{
m_current = m_max;
}
public void SetToMin()
{
m_current = m_min;
}
public bool IsEmpty()
{
return (m_current <= m_min);
}
/// <summary>
/// Set/Get the current value as a percentage of the min and max values
/// </summary>
public float Percent
{
get
{
return ((m_current - m_min) / (m_max - m_min)) * 100;
}
set
{
m_current = m_min + ((value / 100) * (m_max - m_min));
}
}
/// <summary>
/// if this is 'true', then the current value will loop between min and max values instead of being capped.
/// Default: false
/// </summary>
public bool LoopValues
{
get
{
return m_loopValues;
}
set
{
m_loopValues = value;
}
}
/// <summary>
/// Tells you if the current range value is at the maximum value
/// </summary>
/// <returns></returns>
public bool IsMax()
{
return m_current == m_max;
}
/// <summary>
/// Tells you if the current range value is at the minimum value
/// </summary>
/// <returns></returns>
public bool IsMin()
{
return m_current == m_min;
}
}
}
[/CODE]

Share this post


Link to post
Share on other sites
If you want to share code publicly, the proper place to do it is on something like github or bitbucket. And instead of saying "You're free to use it in any way with no strings attached and no guarantee of fitness/correctness", it would be better include a proper source code license file with your code.

Also, if you want your code to be "tested", you should actually write tests for it. If you don't know how, do some research on unit testing and NUnit. You can include the test code with your code above. Otherwise, I not consider this to be "tested" code, now matter how many manual tests you performed.

Hope that helps.

Share this post


Link to post
Share on other sites
[quote name='thok' timestamp='1348610184' post='4983759']
And instead of saying "You're free to use it in any way with no strings attached and no guarantee of fitness/correctness", it would be better include a proper source code license file with your code.[/quote]
Agreed.

[b]@slayemin[/b]: Here's some licenses that you might want:

Suggestion for "[i]free to do whatever[/i]": [url="http://en.wikipedia.org/wiki/MIT_License"]MIT license[/url]
Suggestion for "[i]free to do whatever but give me credit and share changes[/i]": [url="http://www.gnu.org/copyleft/lesser.html"]LGPL[/url]

Suggestion for "[i]I don't care [/i][i]at all[/i][i], just use the code if you want![/i]": [url="http://en.wikipedia.org/wiki/Public_domain"]Public domain[/url] ((this isn't actually a license) [size=2]This only works for countries that have public domain, and you can just ignore the countries that don't - people in those countries will use it anyway and it becomes their problem[/size])

For art, music, photographs, and other non-code works, see [url="http://creativecommons.org/"]Creative Commons[/url]. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Similar Content

    • By Chamferbox
      Chamferbox, a mini game asset store has just opened with some nice game assets, 
      Here you can find a free greek statue asset 

      Also check their dragon, zombie dragon and scorpion monster out:



      They're running the Grand Opening Sale, it's 30% off for all items, but for gamedev member, you can use this coupon code:
      GRANDOPEN
      to get 50% off prices What are you waiting for, go to
      http://chamferbox.com
      and get those models now!

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By DevdogUnity

      Ho ho ho
      Tis the season of Christmas surprises, and we have a awesome one for you! 🎅  
      Sponsored by all your favorite Unity Asset Store developers, Nordic Game Jam, Pocket Gamer Connects, and co-hosted by Game Analytics, we (Joris and I – Devdog) are launching the second edition of our yearly Christmas Giveaway Calendar for all Unity game developers!
      You can already now sign up right here.
       
      So what’s this all about?
      For the past weeks, we’ve been collecting sponsored gifts related to Unity (asset vouchers, product keys, conference tickets etc.), and throughout each day of December leading up to Christmas Day on the 25th, we will be sending out these sponsored gifts as early gamedev Christmas presents via e-mail to hundreds of lucky winners.
      The total prize pool is at $35,000, with over 1200 presents donated by the awesome sponsors!
       
      Merry Christmas from Devdog, Game Analytics, and every single one of the sponsors.

      View full story
    • By sveta_itseez3D
      itSeez3D, a leading developer of mobile 3d scanning software, announced today a new SDK for its automatic 3D avatar generation technology, Avatar SDK for Unity. The Avatar SDK for Unity is a robust plug-n-play toolset which enables developers and creatives to integrate realistic user-generated 3D avatars into their Unity-based applications. SDK users can allow players to create their own avatars in the application or integrate the SDK into their own production processes for character design and animation.
      “Virtual avatars have recently become increasingly popular, especially in sports games and social VR apps. With the advance of VR and AR, the demand to get humans into the digital world is only increasing”, said Victor Erukhimov, itSeez3D CEO. “Our new Avatar SDK for Unity makes it super-easy to bring the avatar technology into any Unity-based game or VR/AR experience. With the Avatar SDK for Unity now every developer can bring face scanning technology into their games and allow players to create their own personalized in-game avatars, making the gameplay much more exciting and immersive.”
      Key features of the Avatar SDK for Unity:
      Automatic generation of a color 3D face model from a single selfie photo in 5-10 seconds (!). Works best with selfies, but can be used with any portrait photo.
      Shape and texture of the head model are unique for each person, synthesized with a deep learning algorithm crafted by computer vision experts
      Head models support runtime blendshape facial animations (45 different expressions)
      Generated 3D heads include eyes, mouth, and teeth
      Algorithms synthesize 3D meshes in mid-poly resolution, ~12k vertices, and ~24k triangles
      Six predefined hairstyles with hair-recoloring feature (many more available on request)
      Avatar generation API can be used in design-time and in run-time, which means you can allow users to create their own avatars in your game
      Cloud version is cross-platform, and offline version currently works on PCs with 64-bit Windows (support for more platforms is coming soon)
      Well-documented samples showcasing the functionality.
       
      Availability
      The Avatar SDK for Unity is offered in two modes - “Cloud” and “Offline”. The “Cloud” version is available at http://avatarsdk.com/ and the “Offline” version is available by request at support@itseez3d.com.
      ###
      About itSeez3D
      At itSeez3D, we are working on the computer vision technology that turns mobile devices into powerful 3D scanners. itSeez3D has developed the world's first mobile 3D scanning application that allows to create high-resolution photorealistic 3D models of people's' faces, bodies and objects. The application is available for iOS and Windows OS mobile devices powered with 3D cameras. In 2016 the company introduced Avatar SDK that creates a realistic 3D model of a face from a single selfie photo. To learn more about itSeez3D scanning software and 3D avatar creation technology, please visit www.itseez3d.com and www.avatarsdk.com.

      View full story
    • By khawk
      Unity has posted the Unity Austin 2017 playlist on YouTube. From their tweet:
      View the full playlist at https://www.youtube.com/playlist?list=PLX2vGYjWbI0TI_C4qouDw7MSSTFhKJ6uS or below:
      .

      View full story
  • Popular Now