简体   繁体   English

如何使用访问器设置此变量?

[英]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. 我试图在我的游戏中的LoadContent()下加载一个纹理,然后尝试将其传递到Update()以便在另一个类中将其用于碰撞检测。

Here is my code: 这是我的代码:

Game1.cs 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) Player.cs(暂时保存碰撞信息)

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. LoadContent()还有更多内容,但这与该问题无关。 Same for Update() . Update()相同。 In debug, player.GetTileType(dirt); 在调试中, player.GetTileType(dirt); comes up as null. 出现为空。 It should be "Dirt" if I'm not mistaken. 如果我没记错的话,应该是“ Dirt”。

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 . 代码中的问题是,您始终在创建GetTileType新实例。

In LoadContent you create one instance - let's call it A - and set the Dirt property on that instance. LoadContent您将创建一个实例-我们将其称为A-并在该实例上设置Dirt属性。
But you don't save that instance anywhere, after the method finished, A is out of scope and will eventually be garbage collected. 但是您不会在任何地方保存该实例,方法完成后,A超出范围,最终将被垃圾回收。

In Update you create a new instance - B - and retrieve the value of the Dirt property from it. Update您将创建一个新实例B-并从中检索Dirt属性的值。
Because this is a newly created instance, this is null . 由于这是一个新创建的实例,因此为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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