简体   繁体   中英

How do I use accessors to set this variable?

Should I even use accessors? If not, how can I do this?

I am trying to load a texture in my game under LoadContent() , then trying to pass this into Update() so I can use it for collision detection purposes in another class.

Here is my code:

Game1.cs

public class GetTileType
{
    public Texture2D dirt;
    public Texture2D Dirt
    {
        get
        {
            return dirt;
        }

        set
        {
            dirt = value;
        }
    }
}

public class Main : Game
{
GetTileType getTileType = new GetTileType();

protected override void LoadContent()
{

    getTileType.Dirt = Content.Load<Texture2D>("Dirt");
}

protected override void Update(GameTime gameTime)
{
    Texture2D dirt = getTileType.Dirt;

    player.GetTileType(dirt);

    base.Update(gameTime);
}

Player.cs (holds collision information for now)

public void GetTileType(Texture2D groundTexture)
{
    Tile tile = (Tile)Main.currentLevel.GetTile(0, 0);

    Texture2D texture = tile.Texture;

    if (texture == groundTexture)
    {
        // Write code to handle what to do if the player tries to enter the ground.
    }
}
}

There's more in LoadContent() , but it's irrelevant to this problem. Same for Update() . In debug, player.GetTileType(dirt); comes up as null. It should be "Dirt" if I'm not mistaken.

I feel I am going about this all wrong, but I can't think of any other way to do it. Everything else I've tried turned into a dead-end.

When I start the game, it loads, then just hangs. I have to stop it form the task manager then.

Can anyone tell me what I'm doing wrong? Thank you very much.

The problem in your code is that you are always creating new instances of GetTileType .

In LoadContent you create one instance - let's call it A - and set the Dirt property on that instance.
But you don't save that instance anywhere, after the method finished, A is out of scope and will eventually be garbage collected.

In Update you create a new instance - B - and retrieve the value of the Dirt property from it.
Because this is a newly created instance, this is null .

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