Creating an object from a template

Monkey Forums/Monkey Programming/Creating an object from a template

Raz(Posted 2012) [#1]
I'd like to randomly generate templates for an enemy and then create a set of enemies based upon this template. As a very crude example...

Let's say I create a template where the X speed of the object is 10 and the Y speed is 5. I then want to say create 10 items to match this template and later on generate more items based on this template. I would then have another template where the X speed is 2 and the Y speed is 100 and again generate n enemies from this template.

I guess to summarise I am generating a new instance based on the variables within a preexisting instance.

Is this possible without using reflection, because I'd rather not rely on it for items created during the game (isn't so bad during the initial generation)

Ta!
Chris


muddy_shoes(Posted 2012) [#2]
I'm not sure if I understand what you want entirely but you could have a template data class that you can use to instantiate enemies. Another option would be to use a copy constructor or clone method to reproduce copies of enemies with specific "settings".


muddy_shoes(Posted 2012) [#3]
Examples:

[monkeycode]
Class MonsterValues
Field x:Int
Field y:Int
End

Class Monster
Field x:Int
Field y:Int

Method New(values:MonsterValues)
Self.x = values.x
Self.y = values.y
End

Method New(copy:Monster)
Self.x = copy.x
Self.y = copy.y
End

Method GetValues:MonsterValues()
Local values:MonsterValues = New MonsterValues()
values.x = Self.x
values.y = Self.y
Return values
End

Method Clone:Monster()
Local clone:Monster = New Monster()
clone.x = Self.x
clone.y = Self.y
Return clone
End

End

Function Main()
Local baseMonster:Monster = New Monster()

baseMonster.x = 10
baseMonster.y = 20

Local spawned:Monster

spawned = New Monster(baseMonster.GetValues())
spawned = New Monster(baseMonster)
spawned = baseMonster.Clone()
End
[/monkeycode]


Paul - Taiphoz(Posted 2012) [#4]
You could also create a list of objects or templates, giving them an ID or field that you can use to identifiy them, then when you want to copy one or use one just traverse the list find the id your looking for and pull the values.

would mean having all those values in memory tho, also means you could write those values out to text file and parse them into and outof a list making them easier to manage.


Raz(Posted 2012) [#5]
Yeah that's it Muddy Shoes, thanks :) Now that you've done that, it does seem very obvious that I just pass the object to the new instance and take the values from there!


jpoag(Posted 2012) [#6]
http://en.wikipedia.org/wiki/Prototype

http://en.wikipedia.org/wiki/Factory_(software_concept)