简体   繁体   中英

The name “Monsters” doesnt exist in the current context

I am fairly new to programming and have run into a little problem, so sorry if its a really simple solution but im not getting it .So I'm programming a really simple version of hearthstone for practice. I created a method which generates all 5 of the cards into an array and I'm trying to use that array to make a list which will act as the players decks. However, in the for loop that I'm trying to do this in the Monsters array says it doesn't exist in the current context?

//Generates monsters and magic cards
public static MonsterCard[] GenerateCards()
{
    MonsterCard[] Monsters = new MonsterCard[5];

    Monsters[0].Name = "Lizard King";
    Monsters[0].Attack = 4;
    Monsters[0].Health = 3;

    Monsters[1].Name = "Piggy";
    Monsters[1].Attack = 2;
    Monsters[1].Health = 1;

    Monsters[2].Name = "Great Drake";
    Monsters[2].Attack = 7;
    Monsters[2].Health = 5;

    Monsters[3].Name = "Bear";
    Monsters[3].Attack = 5;
    Monsters[3].Health = 3;

    Monsters[4].Name = "Lion";
    Monsters[4].Attack = 6;
    Monsters[4].Health = 4;

    return Monsters;
}

main():

int main(){
    int number;
    GenerateCards();
    Random rnd = new Random();
    //Player 1 deck
    for (int i = 0; i < 10; i++)
    {
        number = rnd.Next(0, 4);
        Player1.Deck[i] = Monsters[number]; //<-- this Monsters is where the problem comes
    }

}

GenerateCard returns Monsters , but you never catch them locally in main() .

Monster is local to GenerateCards() and dies right when the function finishes executing.

int main(){
     // ..
     MonsterCard[] Monsters = GenerateCards();
     // ..
}

The above will solve that problem since you return Monsters from GenerateCards() , which has the values you are looking for inside main() .

You have to move your monsters property into a global context.

That's because it is in the scope of another method, so that it's a local variable, only accessible from this method (and it only exists in this method).

An example:

void m1 ()
{
    int a;
    //a exists
    {
        int b;
        //a and b exist
    }
    //only a exists
}
//nothing exists

void m2 ()
{
    //still nothing exists
    int c;
    //Only c exists
}

Variables only exist in their enclosing scope . That means, if you define a variable outside of a method, it exists for all methods:

int a;
void m1 ()
{
    //a exists
}

void m2 ()
{
    //a still exists
}

To learn more about this, read through this .

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