Home > database >  Using Discord.Net (c#) to build a simple slash command bot, but one of my variables changes once it
Using Discord.Net (c#) to build a simple slash command bot, but one of my variables changes once it

Time:12-03

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord.Interactions;

namespace StorytimeBot.v2.Modules
{
    public class Commands : InteractionModuleBase<SocketInteractionContext>
    {
        [SlashCommand("roll", "Roll A D20!")]
        public async Task Roll(int xD20, int bonus)
        {
            string diceRolls = "";
            for (int i = 1; i <= xD20; i  )
            {
                Random r = new Random();
                int dc = r.Next(1, 21);
                diceRolls  = $"Roll {i}: {dc}   {bonus} = {dc   bonus}\n";
            }
            
            await RespondAsync(diceRolls);
        }

This is the snippet of the command that is not doing what is expected. The goal is to put all the strings made in the loop into one variable then print it in discord. However, the variable "dc" does not keep the individual random iterations, but instead all the numbers come out the same. I find this odd and have no clue why it doesn't work when the variable "i" increments properly. Mind that no errors or warnings pop up in the editor.

I have tried multiple solutions like using arrays, using ReplyAsync at the end, and lists, but dc still only keeps one value. There is a way for the code to work by putting ReplyAsync in every iteration of the loop and changing the = to =, but that prints multiple messages into discord for each iteration. Making it slow, so I would like to see if there is anything I can do to avoid having to use the slow solution.

CodePudding user response:

if i am understanding your question correctly the problem is that the random number generator gives the same numbers every time right? If so i think it's best to take the Random r = new Random(); out of the for loop and place it before it.

  • Related