Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Creating a dynamic variable in C#

Discussion in 'Scripting' started by ChrisButler, Dec 6, 2014.

  1. ChrisButler

    ChrisButler

    Joined:
    Nov 15, 2012
    Posts:
    48
    I'm starting work on a Virtual tabletop of sorts, but I need to be able to allow people to dynamically create variables. For example if the character Dominic has "strength" of 15, then I need the code to create int strength = 15, and then later be able to access it as a part of a math problem aka "swordSlashRoll = strength+meleeAttack+(random.next(1,21)". This will let any game able to be played on it, without being system specific.
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    So I'd have a type that you can store a value in, and also define what type of value it is.

    I actually wrote one of those a while back and have it available on my spacepuppy framework:
    https://code.google.com/p/spacepupp...owse/trunk/SpacepuppyBase/VariantReference.cs

    Note, I wrote this with the expectation that it be serializable as well.

    Next, for associating the 'name' of the property with the value. I'd have a Dictionary of strings (for the name) to this VariantReference.

    The keys in the dictionary would be your "variables" and the values the value defined for that "variable".
     
  3. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Your best option without getting into void pointers would be a class you can store values in. Include every type you think you'll need, like a numeric value and a description.

    Code (CSharp):
    1. int value;
    2. string description;
    Those values already are enough to give you players, monsters, spells and items. You just need a way to organize them.
     
  4. ChrisButler

    ChrisButler

    Joined:
    Nov 15, 2012
    Posts:
    48
    I've never dealt with a Dictionary yet. Unfortuantely making an class for them I can't do since I've no idea what their going to need, there are hundreds of different RPG's to reference.
     
  5. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    That's the idea in making a class that is a simple structure of a string and a number. Or even two strings. No matter what it is they are going to need, they aren't going to need more than a description and a numeric value or a collection of descriptions and values. If you break down what items, enemies, players and stats are on paper, you come down to just a value and description.