views:

49

answers:

3

Hello,

I'm having a problem when using variables in object names.

I have a Public class which is called "Tank" In that class, there is a public property called "direction" of an integer type.

I keep getting the error: "Tank is a type and cannot be used as an expression" What I'm doing wrong here ?

Public Class mainroutines()

' Create Instances of tank  

Private Tank1 As New Tank()
Private Tank2 As New Tank()

'Loop trough objects and set the property value

dim i as integer
For i = 1 to 2
Tank(i).direction = 1
next i

End class
A: 

Well, Tank(i) is not equivalent to Tank1. You would need to make a list of tanks, add your instances to it, and access them that way.

Public Class mainroutines() 

' Create Instances of tank '  

Dim allTanks As List(Of Tank) = New List(Of Tank) 
allTanks.Add(New Tank())
allTanks.Add(New Tank())

'Loop through objects and set the property value '

dim i as integer 
For i = 1 to 2 
allTanks(i).direction = 1 
next i 
jball
+1  A: 

Hi there.

You don't have an array of Tanks:

Public Class mainroutines()

' Create Instances of tank  

Private Tank1 As New Tank()
Private Tank2 As New Tank()

'Loop trough objects and set the property value
Dim tanks() As Tank

tanks(0) = Tank1
tanks(1) = Tank2

For i As Integer = 1 To 2
   tanks(i).direction = 1
next

End class

If you're using Visual Studio 2008 then you could use:

Private Tank1 As New Tank() With { .Direction = 1}
Private Tank2 As New Tank() With { .Direction = 1}

So you don't need the For loop at all.

Cheers. Jas.

Jason Evans
Thanks for the answersThe loop was just ment as an example.I'm writing a game and I need a tank for player 1 and one for player 2. player is a variable of the integer type and is 1 or 2 depending on the player which is in controlIn my code I often need to change the direction, or the x,y coordinates of the tank and I like to reference to the tank as Tank(player).directionor Tank(player).X += 5or Tank(player).livesleft -= 1I'll have to test your answers
davidthijs
A: 

@ Jball

It needed a small correction and your example worked just fine ! Exactly what I needed !

Dim alltanks As List(Of Tank) = New List(Of Tank)

Thanks a lot for your help !

davidthijs
Glad to help! I updated my answer with your correction.
jball