0
\$\begingroup\$

In my game when pressing the right mouse button you will place an object on the ground. all objects have the same super class (GameObject). I have a field called selected and will be equal to one certain gameobject at a time. when clicking the right mouse button it checks whats the instance of selected and that how it determines which object to place on the ground. code exapmle: t is the "slot" for which the object will go to.

if (selected instanceof MapleTree) {
    t = new MapleTree(game,highLight);
} else if (selected instanceof OakTree) {
        t = new OakTree(game,highLight);
}

Now it has to be a "new" instance of the object. Eventually my game will have hundreds of GameObjects and I don't want to have a huge if else statement. How would I make it so it scrolls though the possible kinds of objects and if its the correct type then create a new instance of it...?

When pressing E it will switch the type of selected and is an if else statement as well. How would I do it for this too? here is a code example:

if (selected instanceof MapleTree) {
        selected = new OakTree(game);
} else if (selected instanceof OakTree) {
    selected = new MapleTree(game);
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

What about making clones or factories?

For clones, you could just call object.clone(). This would make another instance of this object type. Though I'm not sure if they will share references, so may not be the best way.

Thinking a little more, I think you could use Java Reflection library.

Assuming you just have one constructor with no parameters, this could work:

Constructor ctor = selected.getClass().getDeclaredConstructors()[0];
ctor.setAccessible(true);
t = (GameObject)ctor.newInstance();

If you have parameters for your constructor like in your example you can use something like this:

Constructor ctor = selected.getDeclaredConstructor(game.getClass());

But be aware that this may be slow. So there may be better options for this.

\$\endgroup\$
2
  • \$\begingroup\$ How would I got to implement it here? its a lil hard for me to understand.. \$\endgroup\$ Commented Sep 26, 2012 at 22:59
  • \$\begingroup\$ @gopgop See my edit. it explains clones, and how you could do it better with reflection. \$\endgroup\$ Commented Sep 26, 2012 at 23:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .