0
\$\begingroup\$

When I try to cast an Item as an ImageItem in fails to convert and returns null, hence skipping the code I want to use to extract the texture data. I have already down cast my Item to an ImageItem, and set my TextureItem to public, so I am struggling to see the solution.

Any advice would be greatly appreciated.

Game 1 (Main Class)

ImageItem Downcast

    public class ImageItem : Item
    {
        public Texture2D Texture;

        public List<Color[]> itemTextureDataList = new List<Color[]>();
        public List<Rectangle> itemRectangleList = new List<Rectangle>();
    }

Assign level textures color data to array

        foreach (Layer layer in level.Layers)
        {
            foreach (Item item in layer.Items)
            {
                ImageItem imageItem = item as ImageItem;

                if (imageItem != null)
                {
                    Texture2D texture = imageItem.Texture;

                    imageItemList[iImageItemNum].itemTextureDataList[0] = new Color[imageItem.Texture.Width * imageItem.Texture.Height];
                    imageItem.Texture.GetData(imageItemList[iImageItemNum].itemTextureDataList[0]);
                    iImageItemNum++;
                }
            }
        }

Create a rectangle for every level texture

        foreach (Layer layer in level.Layers)
        {
            foreach (Item item in layer.Items)
            {   
                ImageItem imageItem = item as ImageItem;
                if (imageItem != null)
                {
                    imageItemList[iImageRectNum].itemRectangleList[0] = new Rectangle((int)imageItem.Position.X, (int)imageItem.Position.Y, imageItem.Texture.Width, imageItem.Texture.Height);
                    iImageRectNum++;
                }
            }
        }

Level Class

    public partial class TextureItem : Item

        {
            /// <summary>
            /// The item's rotation in radians.
            /// </summary>
            public float Rotation;

            /// <summary>
            /// The item's scale vector.
            /// </summary>
            public Vector2 Scale;

            /// <summary>
            /// The color to tint the item's texture with (use white for no tint).
            /// </summary>
            public Color TintColor;

            /// <summary>
            /// If true, the texture is flipped horizontally when drawn.
            /// </summary>
            public bool FlipHorizontally;

            /// <summary>
            /// If true, the texture is flipped vertically when drawn.
            /// </summary>
            public bool FlipVertically;

            /// <summary>
            /// The path to the texture's filename (including the extension) relative to ContentRootFolder.
            /// </summary>
            public String texture_filename;

            /// <summary>
            /// The texture_filename without extension. For using in Content.Load<Texture2D>().
            /// </summary>
            public String asset_name;

            /// <summary>
            /// The XNA texture to be drawn. Can be loaded either from file (using "texture_filename") 
            /// or via the Content Pipeline (using "asset_name") - then you must ensure that the texture
            /// exists as an asset in your project.
            /// Loading is done in the Item's load() method.
            /// </summary>
            public Texture2D texture;

            /// <summary>
            /// The item's origin relative to the upper left corner of the texture. Usually the middle of the texture.
            /// Used for placing and rotating the texture when drawn.
            /// </summary>
            public Vector2 Origin;


            public TextureItem()
            {
            }

            /// <summary>
            /// Called by Level.FromFile(filename) on each Item after the deserialization process.
            /// Loads all assets needed by the TextureItem, especially the Texture2D.
            /// You must provide your own implementation. However, you can rely on all public fields being
            /// filled by the level deserialization process.
            /// </summary>
            public override void load(ContentManager cm)
            {
                //throw new NotImplementedException();

                //TODO: provide your own implementation of how a TextureItem loads its assets
                //for example:
                //this.texture = Texture2D.FromFile(<GraphicsDevice>, texture_filename);
                //or by using the Content Pipeline:
                this.texture = cm.Load<Texture2D>(asset_name);

            }
\$\endgroup\$
  • 2
    \$\begingroup\$ item as ImageItem returns null because item is not an ImageItem. What leads you to believe otherwise? When you hover over the variable in the debugger, what type does it claim to be? \$\endgroup\$ – Cole Campbell Aug 28 '13 at 19:22
  • \$\begingroup\$ I thought by Down Casting the Item Class to an ImageItem class would allow me to convert and hence access any Items as ImageItems \$\endgroup\$ – Jon Dunn Aug 29 '13 at 21:30
  • \$\begingroup\$ Downcasting can't turn an object into something that it isn't. It can turn a variable of type Base into a variable of type Derived, but only if the object referenced by the variable is actually of type Derived. \$\endgroup\$ – Cole Campbell Aug 30 '13 at 16:03
3
\$\begingroup\$

Imagine that you are a manufacturer of flanges. You have a great deal of flanges in your possession, more than you can reasonably store in your own garage, so you've purchased a warehouse in which to store your inventory.

One day you receive a large order that must be fulfilled with all haste, so you go to your warehouse manager, Carl the Compiler (whose epithet is a matter of some mystery), and ask him to assist you in doing so.

"What kind of flanges do you need?" Carl asks you.

"It doesn't matter," you say, "the customer just wants 100 flanges."

It just so happens that Carl is sitting on top of a large pile of boxes, each of which is clearly marked as containing a frobnosticating flange. Carl points out that it is trivially provable that all frobnosticating flanges are flanges, and orders that the entire mountain of boxes be immediately shipped to the customer.

This is upcasting.

The next day you receive another order, but this time the client is more specific: rather than requiring any kind of flange, he needs 100 defenestrating flanges. You return to Carl to ask for his assistance.

Unfortunately, it seems that the marketing department has decided to relabel all of the packages in the warehouse. Rather than each box being clearly labeled, they now simply read 'FLANGE' in a tasteful humanist font.

You inform Carl of the new order for defenestrating flanges.

"That could be a bit of a problem," he says. "Ever since marketing relabeled all of the boxes, I have no idea what kind of flange is inside any of them."

You pick one of the boxes at random and hand it to Carl and ask, 'box is DefenestratingFlange?'

He opens the box and pulls out the frobnosticating flange inside. 'false,' he replies.

Fortunately, you suddenly remember that you had specifically set aside 100 defenestrating flanges earlier that week, hiding them away in a unused room so that nobody else would take them. You go to the room and, lo and behold, the boxes are still there, though they—like all the rest—have been 'updated' with the new labels.

You carry these boxes out to Carl and tell him to ship them to the customer with all haste.

"But I can't verify that these are defenestrating flanges," he objects.

"That's fine," you tell him, "I have special knowledge that they are. I'm the boss, and you can trust me to know what I'm talking about, so just do it."

Carl accepts this and does as you ask.

This is downcasting.

You then realize that you've misplaced one of the boxes, leaving you one flange short of the 100 that were ordered. To rectify this, you retrieve a random box from the warehouse—not bothering to check what's actually inside—and throw it in with the rest.

'InvalidCastException,' Carl complains.

You open the box. There's a frobnosticating flange inside.

Well, nobody's right all the time.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.