Search code examples
c#listnames

Querying object without a given name


I have created a list of objects using a C# line like this:

gameObjects.Add(new Object());

I have also made a function that prints on the screen a list of the object types contained within gameObjects.

for(int i = 0; i < gameObjects.Count; i++)
  Console.WriteLine(gameObjects[i].GetType());

So far so good. However I'm getting more items printed on the screen than should be present in gameObjects, so I've been trying to work out a way of finding out whether any of the entries are duplicates as I can't find anything in my code that could be creating extra objects in the list. It would be great if I could print out the names of each object in the list, but as I haven't given them names I don't think this is possible. Is there anything else that would differentiate one object in the list from another that I could take advantage of? As it's just debugging, I didn't really want to have to go in and make sure each object is given a name.

Thanks!

Edit:

For those asking for more code, I have a function that adds objects of type staticObject to the gameObjects list:

private void CreateStaticObject(Vector2 v2StaticObjectPosition)
        {
            Texture2D staticObjectTexture = Content.Load<Texture2D>(@"textures\StaticObject");
            GameInfo.gameInfo.gameObjects.Add(new StaticObject(staticObjectTexture, v2StaticObjectPosition, sbSpriteBatch));
        }

The list is contained within a class called GameInfo. Each StaticObject inherits from a Sprite class, if that's of importance.

I also add a Player object to the list, which inherits from the StaticObject class:

private void CreatePlayer(Vector2 v2PlayerPosition)
        {
            Texture2D playerTexture = Content.Load<Texture2D>(@"textures\Player1");
            player1 = new Player(playerTexture, v2PlayerPosition, sbSpriteBatch);
        }

I'm then printing out the contents of the list with this:

for(int i = 0; i < GameInfo.gameInfo.gameObjects.Count; i++)
            {
                string sObjectString = string.Format("Game object {0} is a {1}", i, GameInfo.gameInfo.gameObjects[i].GetType());
                DrawWithShadow(sObjectString, new Vector2(10, 20 * i + 10));
            }

DrawWithShadow() is just a simple method which nicely formats the text on the screen in the desired location. Unfortunately though, for each object that I create by calling the CreateStaticObject() method, I end up with two entries in my list.


Solution

  • Thanks for all the suggestions guys. However I've discovered the source of my problem. I had an old line of code in the constructor for the StaticObject class which adds any created StaticObject to the list. So I was adding each object twice. D'oh! :S