在XNA中的类中使用静态Texture2D

时间:2012-03-31 23:51:12

标签: c# xna pass-by-reference

在XNA中,在init之后调用load内容,这是公平的,但是它导致了加载纹理的一些问题。

在Init中,我将sprite的spriteTexture设置为Static Texture2D的spriteTexture。

在LoadContent i中,然后设置Static Texture2D的值。这很有效。

然而,当涉及到Draw()方法时,spriteTexture值仍为null,从而导致它失败。我怎么能克服这个?

感觉它与传递价值而不是参考有关。有帮助吗?

谢谢, 丹尼

代码: http://pastebin.com/C92ADY7s

4 个答案:

答案 0 :(得分:0)

在调用构造函数之前必须调用LoadContent方法。否则,纹理不会被加载,并且spriteBatch被赋值为null(spriteBatch=null;),因此未分配引用,后来的纹理loding也没有效果。

答案 1 :(得分:0)

构造函数将在LoadContent之前调用。那时,switch语句中的行都会将null分配给spriteTexture。

最简单的解决方法是保存requestedMenuButtonType的值并将switch语句(或对包含switch语句的方法的调用)放入LoadContent(在之后的某个点)图标已加载)。例如:

private static MenuButtonType savedMenuButtonType;

public MenuButton(int requestedX, int requestedY, int requestedWidth, int requestedHeight, MenuButtonType requestedMenuButtonType)
   : base(requestedX, requestedY, requestedWidth, requestedHeight)
   {
      ...
      savedMenuButtonType = requestedMenuButtonType;
      ...
   }

public static void LoadContent(ContentManager Content)
{
   ...
   //Main Menu Icons
   ...
   //About Menu Icons
   ...
   spriteTexture = GetRequestedSpriteTexture();
}

private static Texture2D GetRequestedSpriteTexture()
{
   switch (savedMenuButtonType)
   {
      case MenuButtonType.play:
         return playButtonIcon;
         break;

      ...
}

更好的解决方案可能是将Texture2D包装在某个Icon类中,该类具有自己的LoadContent方法(为其特定{{1}调用LoadContent }})。然后,当调用LoadContent时,它将加载Texture2D而不丢弃Icon引用。

Texture2D

答案 2 :(得分:0)

如果你只是加载少量/少量纹理(不费时),jou就可以在MenuButton构造函数中调用加载内容。

答案 3 :(得分:0)

这是因为引用在C#中的工作方式。这是一个使用字符串而不是纹理的简单示例:

String foo = null; // A null reference is assigned to the foo variable...

String bar = foo; // The null reference is *copied* to the bar variable. We now have 2 distinct references..

foo = "foo"; // The foo variable is *overwritten* with a new reference to the string...

bar != "foo"; // The bar variable is not affected at all, its own reference still points at null.

现在,如果您想在加载之前引用纹理,则需要为实际的Texture2D成员提供一个间接级别,从而避免复制空引用以开始...

static public Icon
{
    public Texture2D Texture; // starts with null...

    static public Icon PlayButton = new Icon(); // Not a null reference, even though the texture hasn't been loaded yet...
}


public class MenuButton
{
    public MenuButton()
    {
        this.Icon = Icon.PlayButton; // Again, not a null reference...
    }

    public Icon Icon { get; set; }

    public void Draw()
    {
        SpriteBatch.Draw(this.Icon.Texture); // etc...
    }
}

现在只要我们调用load内容(Icon.MenuButton.Texture = Content.Load(“blah.png”);),我们的draw方法就可以工作*:)

现在,当Icon.Texture属性被更改/覆盖/之后,MenuButton类不受影响,因为它只保存对Icon类实例的引用,该实例不会更改。

*我真的很想在Icon类中添加一个draw方法。或者甚至是SpriteBatch的扩展方法直接绘制一个Icon引用...这更符合'tell don't ask'原则:)