开发者

VB.net list(of T) not returning indexed object

I'm working on a small game that is based on a map of grid squares. I have a class (clsGrid) that stores a few properties for each grid square. The grid square objects are organized into a list(of clsGrid).

A loop and stream reader are successfully reading properties from a text file, putting the properties into grid objects, and adding the grid objects to a my list of grids. When retrieving a grid from the list of grids, I'm getting unusual results. Regardless of the index I give the list, I always seem to get the last indexed grid in the list. The debugger seems to suggest that the right numbers are being read into the stream reader and they are being added to gridHolder. However, the message box at the end will always show me the LAST grid.id, regardless of the index I give it.

I've been working on this so long it's probably something stupid. Thanks in advance for the help.

'A subroutine that generates a map (list of grids)
Sub GenerateMap()
    Dim reader As StreamReader = File.OpenText("map1.txt")
    Dim gridHolder As New clsGrid

    'The streamreader peeks at the map file.  If there's nothing in it, a warning is displayed.
    If reader.Peek = 开发者_运维技巧CInt(reader.EndOfStream) Then
        MessageBox.Show("The map file is corrupted or missing data.")
        reader.Close()
    Else
        'If the map file has information, X and Y counts are read
        intXCount = CInt(reader.ReadLine)
        intYCount = CInt(reader.ReadLine)

        'Reads in grid properties until the end of the file
        Do Until reader.Peek = CInt(reader.EndOfStream)
            gridHolder.TerrainType = CInt(reader.ReadLine)
            gridHolder.MovementCost = CInt(reader.ReadLine)
            gridHolder.DefensiveBonus = CInt(reader.ReadLine)
            gridHolder.ID = listMap.Count
            listMap.Add(gridHolder)
        Loop
        reader.Close()
    End If
End Sub

'This function returns a Grid object given an X and Y coordinate
Function lookupGrid(ByVal intX As Integer, ByVal intY As Integer) As clsGrid
    Dim I As Integer
    Dim gridHolder As New clsGrid

    'This formula finds the index number of the grid based on its x and y position
    I = ((intX * intYCount) + intY)
    gridHolder = listMap.Item(I)
    MessageBox.Show(gridHolder.ID.ToString)

    Return gridHolder
End Function


In GenerateMap, your Do Until loop is adding a reference to the same clsGrid instance (gridHolder) to the list each time through. Since all of your list items are referencing the same instance, your message box shows the same results regardless of the index I.

You need to create a new instance of clsGrid each time through the loop. One way to do this is to add the line "gridHolder = New clsGrid" as the first line in your loop. You can then also delete the word "New" from your existing Dim statment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜