Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a function modify a variable C# [closed]

Hi I am extremely new to C# and programing in general. I'm trying to make a text based adventure game as my first unguided project. I am sorting all of the attack/damage rolls into functions. But I cannot get functions to modify variables.

Does anyone know how I can get a function to modify a variable globally.

EXAMPLE CODE

class Program
{
public static int var = 10;

    static void Main(string[] args)
    {
        Maths();
        Console.WriteLine(var);
    }

    static void Maths()
    {   
        int var = 12;
    }
}

In this example I want the modified "var" to be printed as 12 but instead "var" is printed as 10.

This is my actual code which I want to use this principle in.

class Program
{
    //Char Stats
    static int playerMaxHealth = 50;
    static int playerHealth = 40;
    static int playerAttack = 10;
    static int playerLevel = 1;

    //Temp Stats
    public static int attackRoll;

    //Enemy Stats
    static int enemyMaxHealth;
    static int enemyHealth;
    static int enemyAttack;

    //Declar Random
    static Random randomObject = new Random();



    static void Main(string[] args)
    {
        attackRollFunc();
        Console.WriteLine(attackRoll);
        while(true)
        {
            if (playerHealth <= 0)
                death();
        }
    }


    public static int attackRollFunc()
    {
        int attackRoll = randomObject.Next(playerAttack);
        Console.WriteLine(attackRoll);
        return attackRoll;
    }
like image 757
icestroge Avatar asked Jan 19 '26 13:01

icestroge


1 Answers

In the code

static void Maths()
{   
    int var = 12;
}

You are declaring a new local variable named var. This is unrelated to the var field that you're trying to modify.

If you remove the int part from your method, it will do what you were expecting:

static void Maths()
{   
    var = 12;
}
like image 134
Tim S. Avatar answered Jan 21 '26 02:01

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!