Cleanest way to Spawn Creatures Within a Plugin?

Discussion in 'Plugin Development' started by JMEYER, Feb 4, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    JMEYER

    A little tired, so please pardon anything that is incoherent. I'll help clarify any questions in the morning.

    .
    .

    I have an ArrayList: (inherited - cleaned to contain only Creatures)
    Code:
    ArrayList<LivingEntity> group;
    .

    I have a method:

    Code:
    public void spawnAllScattered(CraftWorld world, double minX,
            double maxX, double minY, double maxY, double minZ, double maxZ) {}
    .

    The body of the method would go something like this:

    Code:
    public void spawnAllScattered(CraftWorld world, double minX,
            double maxX, double minY, double maxY, double minZ, double maxZ) {
        for (LivingEntity le : group) {
            ... spawn le at random point within given area ...
        }
    }
    .
    .

    How can I spawn a LivingEntity in the cleanest way possible? I want to avoid the large if/else statement checking if the LivingEntity is an instance of a class (see below) or using purely Strings to identify the Creature's class.

    Code:
    if (le instanceof CraftPig) {
        ... spawn pig ...
    } else if (le instanceof CraftZombie) {
        ... spawn zombie ...
    } else if (etc.) {
        ... spawn etc. ...
    }

    Many thanks in advance for the help!

    JMEYER
     
  2. Offline

    Luck

    Use a switch statement instead if...else if
     
  3. Offline

    feverdream

    You have a few options.

    If you REALLY dont want multiple if-else, just get the objects name and hash it down to a single letter.. then you can use a single character literal in a switch. Problem with this, is it is more work then just using the if..else..if.. as Java does not support string constants in switch statement, unlike simular languages like C#

    If you wanted to liver like Danger Man, you could use the objects hash codes.. but that can be trippy as you never really know if you will get a hash colision.

    Another possible way is to boil each object down to an enum value and use that in a switch.. but like I said, its less work to just use the if..else conditionals.
     
  4. Offline

    JMEYER

    Enums are not my strong suit, but that sounds much more elegant. Is there a way to directly have the -class- correspond to a String?

    My plugin will require me to take a list of monsters from a SQLite database. I'll have to both add the monsters to the ArrayList using a similar if/else. Then spawn them using that same if/else.
     
  5. Offline

    matejdro

    @Luck how to use switch statement over instanceof? AFAIK switch in java only support integers.
     
  6. Offline

    Kekec852

Thread Status:
Not open for further replies.

Share This Page