Getting a location from a different class

Discussion in 'Plugin Development' started by jamw, Jun 4, 2012.

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

    jamw

    So basically im making a plugin where someone sets a location from a command, so the would do
    /SBG SetTp and it would store their location, now in the listener i want to make it so when they die they go to the location the player set. How do i get it over?
     
  2. Offline

    Malikk

    If you have a variable as a field in one class, you can get it in another class by obtaining an instance of that class.

    Code:
     
    public class Class1{
    int myInt = null;
     
        public void setMyInt(int i){
            myInt = i;
        }
     
    }
     
    public class Class2{
     
        public int getClass1IntExample(){
            Class1 c1 = new Class1();
            return c1.myInt;
        }
     
    }
    
    This might be a kinda awkward example and my classes don't have constructors, etc. but if you have any more questions, just tag me.

    Basically, once you set that field, you can get the value from the instance of that class. I've created the class object in the second class for simplicity of this example. But generally, I would make the instance in your main class so that you can keep it single instance.
     
  3. Offline

    jamw

    @Malikk Um.. I'm sorry i'm lost, lol. Here's my code.
    Main:
    Code:
    public class SnowBall extends JavaPlugin {
        public static SnowBall plugin;
        public final Logger log = Logger.getLogger("Minecraft");
       
        public void onEnable(){
            this.log.info("SnowBall Games Enabled!");
            getServer().getPluginManager().registerEvents(new PListener(), this);
        }
       
        public void onDisable(){
            this.log.info("SnowBall Games Disabled!");
           
        }
       
        public boolean onCommand(CommandSender sender, Command cmd, String cmdlabel, String[] args ){
            Player player =(Player) sender;
            if(cmdlabel.equalsIgnoreCase("sbg") || cmdlabel.equalsIgnoreCase("SnowBallGames")){
                player.sendMessage(ChatColor.GREEN +"SnowBallGames! Please enter a Sub-Command.");
            }else if(args[0].equalsIgnoreCase("tpset")){
            Location location = player.getLocation(); //Heres where they define the location
            }
            return true;
            }
     
    }
    
    Listener:
    Code:
     @EventHandler
    public void onEntityDamageByEntity ( EntityDamageByEntityEvent event )
    {
    Entity damagedentity = event.getEntity();
    Entity damagerentity = event.getDamager();
     
    if( damagerentity instanceof Snowball && damagedentity instanceof Player )
    {
    Player hittedPlayer = (Player)damagedentity;
    int health = hittedPlayer.getHealth();
    hittedPlayer.setHealth(health- 6);
    hittedPlayer.sendMessage("hit");
    }
     
     
    @EventHandler
    public void OnDeath(PlayerDeathEvent event){
     
    Player player = event.getEntity();
    Entity killer = player.getKiller();
    if(killer instanceof Snowball){
    player.teleport( ) //heres where i need to put the location
    }
     
    }
    }
    
    Sorry to bump but...bump

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 26, 2016
  4. For such little code you don't need 2 classes, just move the events inside the main class, implement Listener and use registerEvents(this, this).

    Still, you already have a public static plugin variable (which you didn't asign) which you can use to get that variable... but FIRST you need to make a global Location variable, because you're only storing it in that code block and it's pointless... I belive your editor also tells you that (makes it yellow).

    However, you define one variable for all players, if one player types that command, all players that die will teleport there, if you want each player to set it's own location, then you need a HashMap<String, Location> instead and store/get by player name.

    Some other notes:
    - your plugin will get a ArrayOutOfBounds error if you use the sbg command without any arguments because you're getting index 0 from args without checking if args.length > 0.
    - you shouldn't print enabled/disabled messages because Bukkit already does that and you're making duplicates which cogs up the console
    - you should use getLogger() instead but you shouldn't asign it as you asign the curent one, asign it in onEnable ... but you can just use getLogger() whenever you want to log something... also, the reason for this is that getLogger() will put your plugin name in messages your plugin sends, otherwise it will be anonymous and administrators will be heavily confused about the messages if they don't know where it came from.
     
  5. Offline

    Malikk

    Digi jamw

    Well, he needs to learn how to use more than one class, lol.

    I generally keep all my fields together at the top of my main class so that anywhere in my plugin I can say
    Code:
    plugin.whateverClass
    
    and be able to access its fields.

    Here's a bit of the main class of my EpicGlass plugin.

    Code:java
    1.  
    2. public class EpicGlass extends JavaPlugin{
    3.  
    4. private Logger log = Logger.getLogger("Minecraft");
    5.  
    6. public EGGunsListener gunsListener = null;
    7. public EGConfig config = new EGConfig(this);
    8. public EGBreak breakB = new EGBreak(this);
    9. public EGArrow arrow = new EGArrow(this);
    10. public EGCollision collision = new EGCollision(this);
    11. public EGRegen regen = new EGRegen(this);
    12. public EGBlockHandler blockHandler = new EGBlockHandler(this);
    13. public EGGuns guns = new EGGuns(this);
    14. public EGShield shield = new EGShield(this);
    15. public EGListener listener = new EGListener(this);
    16.  
    17. public ArrayList<EGBlockData> blockData = new ArrayList<EGBlockData>();
    18. public int id = 0;
    19.  
    20. public void onEnable(){
    21.  
    22. config.loadConfiguration();
    23. guns.hookGuns();
    24. shield.hookShield();
    25. loadCommandExecutors();
    26.  
    27. PluginManager pm = this.getServer().getPluginManager();
    28. pm.registerEvents(listener, this);
    29.  
    30. log("Enabled");
    31. }
    32.  
    33. public void onDisable(){
    34. revertAll();
    35. getServer().getScheduler().cancelTasks(this);
    36.  
    37. log("Disabled");
    38. }
    39.  


    See where I've instantiated all the classes? You can then use those variables to access those classes. Any variable declared outside of a method is called a field. These fields can be used by any method in that class as well as from the class object that will be at the top of your main class.
     
  6. Malikk
    I find it very pointless to create a global variable (field) just to point to a class that won't ever change which you'll also use only once.
    That would be only appliable for classes that don't have methods which are usable elsewhere by the plugin... like an Events class.

    You also seem to use the logger with minecraft argument and I suspect you have to manually add the plugin name for the logs... you should also read my previous post :)

    But yeah, passing by reference is just fine, altough you didn't quite explain it.

    jamw to give the event class a value as argument you need to define a constructor that accepts arguments:
    Code:
    public class Events implements Listener
    {
        private YourMainClass plugin;
    
        public Events(YourMainClass plugin)
        {
            this.plugin = plugin;
        }
    
        // then just use plugin.method() or plugin.variable to use the respective method or variable.
    }
    
    // and in your main class in onEnable just:
    getServer().getPluginManager().registerEvents(new Events(this), this);
    Still, there are classes that you can't send your plugin instance by reference, in that case you should have a static field or a static method to get the instance.
     
  7. Offline

    jamw

    @Digi As you can tell, i am a very new coder. I appreciate your explanations but am still very very confused. I would appreciate it if you would give me an example using my code?
     
  8. Here you go, copy paste + modifications:
    Code:
    public class SnowBall extends JavaPlugin {
        protected Location teleportLocation; // < changed
    
        public void onEnable(){
            getServer().getPluginManager().registerEvents(new PListener(this), this); // < changed
        }
       
        public boolean onCommand(CommandSender sender, Command cmd, String cmdlabel, String[] args ){
            Player player =(Player) sender;
            if(cmdlabel.equalsIgnoreCase("sbg") || cmdlabel.equalsIgnoreCase("SnowBallGames")){
                player.sendMessage(ChatColor.GREEN +"SnowBallGames! Please enter a Sub-Command.");
            }else if(args[0].equalsIgnoreCase("tpset")){
            teleportLocation = player.getLocation(); // < changed
            }
            return true;
            }
     
    }
    Code:
    public class PListener implements Listener {
    private SnowBall plugin; // < changed
    
    public PListener(SnowBall plugin) // < changed (this is the constructor)
    {
        this.plugin = plugin;
    }
    
     @EventHandler
    public void onEntityDamageByEntity ( EntityDamageByEntityEvent event )
    {
    Entity damagedentity = event.getEntity();
    Entity damagerentity = event.getDamager();
     
    if( damagerentity instanceof Snowball && damagedentity instanceof Player )
    {
    Player hittedPlayer = (Player)damagedentity;
    int health = hittedPlayer.getHealth();
    hittedPlayer.setHealth(health- 6);
    hittedPlayer.sendMessage("hit");
    }
     
     
    @EventHandler
    public void OnDeath(PlayerDeathEvent event){
     
    Player player = event.getEntity();
    Entity killer = player.getKiller();
    if(killer instanceof Snowball){
    player.teleport(plugin.teleportLocation) // < changed
    }
     
    }
    }
    }
    If you want to log something in the main plugin just use getLogger().info/severe/warning/etc()., in the listener just use plugin.getLogger()....().

    You should also indent your code... every IDE has an format feature (for eclipse, see here: http://forums.bukkit.org/threads/how-to-make-eclipse-clean-up-format-your-code-for-you.78574/)
     
  9. Offline

    jamw

    @Digi
    Oh my god! that was so simple! i don't know why i couldnt understand that.. Also thank you very much for the coding tips too! I will deffinetly note all those.
     
Thread Status:
Not open for further replies.

Share This Page