greyspace
greyspace

Reputation: 545

Unexpected symbol `=' in class, struct, or interface member declaration

I am getting the above error for the following code:

public class Sheep : Animal {
    //hpMax = 100;
    //power = 10;
    //defense = 10;
    //speed = 10;
    animalName = "Sheep Test";

    public override void Attack()
    {
        Debug.Log(animalName);
    }

}

It appears that I can't assign variables outside of a method. Is this the case? That would mean I'd have to create a "AssignStats()" method to assign HPMax, power, defense, speed, etc. I think it's probably clear why I want to avoid adding this added step to the code every time I call an animal object.

Or am I missing something obvious?

Upvotes: 0

Views: 7555

Answers (1)

T McKeown
T McKeown

Reputation: 12857

You are missing a type declaration for your animalName attribute.

If animalName is declared in the base class as a protected variable you could set the animalName in the constructor like this:

public Sheep() : base(){
   animalName = "Sheep Test";
}

This assumes that the Animal class is defined similar to this:

public class Animal{
   protected string animalName;  //protected allows descendent classes 
                                 //direct access to the var.
}

Upvotes: 4

Related Questions