简体   繁体   中英

Accessing class objects from different functions

How can I access a class object from different functions? So I have:

Player player1 = new Player();
Player player2 = new Player();

Inside my void main function.

But when I try to get: player1.name from fight function (a new function I have created) player1 isn't recognized.

How can I share the class player1 between my functions?.

I can basically give the player1 info to the function 'fight' using function parameters but in case I have 50 parameters to pass it's hard.

Thanks everybody!

I have tried to call the class player1 from different functions but it was an error.

static void Main(string[] args) {
        Player player1 = new Player();
}

public void fight(){
        Console.WriteLine(player1.name);

}

Your question is a matter of scope. Depending on where you declare your variables, they are only visible within a certain scope. There are many sites that explain this concept, but here's one:

https://www.geeksforgeeks.org/scope-of-variables-in-c-sharp/

In answer to your question, you can declare your variables as 'global' and then have access to them in any function in your class.

You can make them global by taking your declaration, ie Player player1 = new Player(); and then moving it outside of your void main method, so that it's not inside of any method, but still inside your class. You will then be able to access and modify the values of that variable in any function in that class.

You should also check out access modifiers like private,public, protected, etc. to see how other classes might access those variables.

You need to pass the Player object as a parameter to the function fight. Example:

static void Main(string[] args)
{
    Player player1 = new Player();
}
public void fight(Player player)
{
    Console.WriteLine(player.name);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM