vendredi 26 décembre 2014

Instantiating various inherited classes through one method, without reflection

In a project I'm working on, I have a set of blocks that make up a 3D voxel based environment (like Minecraft). These worlds are stored in an external data file.


This file contains the data for: Each block, its location, and its type.


When the LoadLevel method is called, I want it to iterate over the data for every block in the file, creating a new instance of the Block object for every one. It's no problem to pass things like location. It's as simple as



CreateBlock(Vector3 position)


The issue is with the type. All types are child classes (think Abstract Block, and then subtypes like GrassBlock or WaterBlock that inherit the abstract Block's properties.) Assuming there's a child class like "GrassBlock" that I want to be created, rather than a generic block, how do I make it do this through the method? The only way I know of is through reflection, which I've been advised to stay away from. Is it possible that I can do this through generic typing or something?


This seems like such an important question in game design, but no one I've asked seems to have any idea. Any help?






Aucun commentaire:

Enregistrer un commentaire