Search Unity

tweaked RNG

Discussion in 'Getting Started' started by killerKeks26601, Apr 17, 2021.

  1. killerKeks26601

    killerKeks26601

    Joined:
    Jan 13, 2021
    Posts:
    31
    Hello,
    I am currently working on something like a chatbot and it's supposed to be highly customisable.
    All the messages have tag's and when you send it a message it is supposed to find a random message inside on of the tags.
    Only that you can tweak the chances of a message appearing.
    My idea was to define an int in the message class, that can be changed by the user, to tell the RNG how many spot's are reserved for that message.
    I've written some code for this but I dont know how to make unity remember what range stands for what message.
    Code (CSharp):
    1. public List<Tag> tags = new List<Tag>();
    2.     public Message GetMessage(Message message)
    3.     {
    4.         int randomIndex = Random.Range(0, message.tags.Count);
    5.         Tag tag = tags.Find(i => i.tag == message.tags[randomIndex]);
    6.         int hundredPercent = 0;
    7.         foreach(Message message1 in tag.messages)
    8.         {
    9.             hundredPercent += message1.tier;
    10.         }
    11.         int winner = Random.Range(1, hundredPercent);
    12.         return winner;
    13.     }
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    This is called a weighted random choice or a probabilistic choice. You can find a number of implementations of this over at RosettaCode (though none yet for MiniScript... I may need to fix that!).

    Basically you pick a number between 0 at the total; then compare this to the weight of each choice, subtracting that wait from the number you picked until you find a choice whose weight is bigger than the number.