This site requires JavaScript, please enable it in your browser!
Greenfoot back
Electrk
Electrk wrote ...

2013/3/28

Spawning an Actor from a string?

Electrk Electrk

2013/3/28

#
How do I spawn an Actor from a string? That is, if someone were to put "Wombat" in a string, how would I make it spawn a Wombat from that string? Or if they put "Apple" it would spawn an Apple, etc.
azazeel azazeel

2013/3/28

#
how can you get the String ? How many option do user have to choose/put ? Are those option object(s) or class(es) ?
danpost danpost

2013/3/28

#
You would have to programmatically change each String value to the appropriate class, and then create new instancees of the class from there.
Class clss = null;
if ("Wombat".equals(actorString)) clss = Wombat.class;
if ("Apple".equals(actorString)) clss = Apple.class;
// etc.
See my response to your other discussion on converting a class to an actor.
davmac davmac

2013/3/28

#
I don't recommend using reflection for this. If you want a string to specify which actor to create, just create a different actor based on the string. To modify the above example:
Actor actor = null;
if ("Wombat".equals(actorString)) actor = new Wombat();
if ("Apple".equals(actorString)) actor = new Apple();
// etc
Electrk Electrk

2013/3/30

#
Better question: How do I convert a String to an Actor?
danpost danpost

2013/3/30

#
davmac wrote...
If you want a string to specify which actor to create, just create a different actor based on the string.
Actor actor = null;
if ("Wombat".equals(actorString)) actor = new Wombat();
if ("Apple".equals(actorString)) actor = new Apple();
// etc
Do you mean by casting? Because that wouldn't work. What you would have to make a method that would allow user input, then have another method (or the same one depending on how you write it) that spawns an actor based off what the input was. I would do something like this:
public void createActor()
{
    spawnFromString(askForInput());
}

public String askForInput()
{
    return //However you ask for input
}

public void spawnFromString(String str)
{
    if (str.equals("Wombat"))
        spawnActor(new Wombat(), world);
    if (str.equals("Apple"))
        spawnActor(new Apple(), world);
    //etc.
}

public void spawnActor(Actor a, World w)
{
    w.addObject(a, //x, //y);
}
danpost danpost

2013/3/30

#
It is already being cast to an Actor type:
Actor actor = null; // actor is type cast to retain an Actor object
if ("Wombat".equals(actorString)) actor = new Wombat();
if ("Apple".equals(actorString)) actor = new Apple();
// etc
getWorld().addObject(actor, /* x, y */);
You need to login to post a reply.