Question about Objects
BlitzMax Forums/BlitzMax Beginners Area/Question about Objects
| ||
What I want to do is create an object but it depends on the user input what kind of object will be created. The following code doesn't work for me, please can you help me how to do this right? Local P1:Player = New Player; Local UserSetup:Setup = New Setup; Local Weap:String = UserSetup.getWeap(); Select Weap Case "MP5" Global MyGun:MP5 = New MP5; Case "UMP" Global MyGun:MP5 = New UMP; EndSelect Repeat P1.Move(); MyGun.Update(P1.X, P1.Y); Until KeyHit(KEY_ESCAPE) I deleted all unnecessary code. MP5 and UMP are extended types of a firearm type which is a extended class of a weapon type. The method update is declared in my weapon type. Now when I try to compile this the compiler says: "Identifier 'MyGun' not found." Why? I declared it in my 'select Weap' part as global. |
| ||
a couple things: a) try declaring MyGun above the select. i think the not found error is caused by it being declared inside of the select b) if i understand correctly, MyGun should probably be declared of type Firearm (or whatever both MP5 and UMP are based on) since both MP5 and UMP belong to type Firearm. unless MP5 is extended from UMP you shouldnt be able to store a UMP instance into an MP5 variable. so the modifications would look like: Local P1:Player = New Player; Local UserSetup:Setup = New Setup; Local Weap:String = UserSetup.getWeap(); Global MyGun:Firearm Select Weap Case "MP5" MyGun = New MP5; Case "UMP" MyGun = New UMP; EndSelect Repeat P1.Move(); MyGun.Update(P1.X, P1.Y); Until KeyHit(KEY_ESCAPE) |
| ||
Well since your code doesn't compile in a meaningful way, here is an example of using polymorphism to solve this problem: |