How to get the declared variable

61 views Asked by At

When i try to print the variable from another class, it prints the undeclared variable, so only 0.

Here is an example:

public class Player
{

Enemy enemy;

public void Initialize(){
enemy = new Enemy();
}

public void Update()
{
Console.WriteLine(enemy.Rectangle);
}

}

public class Enemy()
{

public Rectangle Rectangle;

public void Update()
{
Rectangle = new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height);
}

}
1

There are 1 answers

4
Reza Jenabi On

I think the following code can help you

public class Player
{

        Enemy enemy;

        public void Initialize()
        {
            enemy = new Enemy();
        }

        public void Update()
        {
            enemy.Update();
            Console.WriteLine(enemy.Rectangle);
        }

    }

    public class Enemy
    {

        public System.Drawing.Rectangle Rectangle;

        public void Update()
        {
            Rectangle = new System.Drawing.Rectangle(5, 10, 10, 10);
        }

}

Main:

Player p = new Player();
p.Initialize();
p.Update();

Result:

enter image description here

enter image description here