简体   繁体   English

Bukkit插件-监听器未运行?

[英]Bukkit plugin - Listener not running?

Hi I'm having this problem with my code everytime I make an object in a Listener class the listener won't work eg 嗨,每次我在Listener类中创建对象时,我的代码都会遇到此问题,例如,侦听器将无法工作

I have this public variable in my main class (CSmain.java): 我的主类(CSmain.java)中有这个公共变量:

public static Location spawn;

I also have a method in that class called getSpawn() which returns spawn: 我在该类中还有一个名为getSpawn()的方法,该方法返回spawn:

public Location getSpawn(){
    return spawn;
}

I have initialized the variable in my onEnable() but when I try to get it from my other class the class (JoinListener.java) won't work eg 我已经在我的onEnable()中初始化了变量,但是当我尝试从其他类中获取该变量时,该类(JoinListener.java)将无法工作,例如

@EventHandler
    public void onJoin(PlayerJoinEvent event){

        CSmain mainClass = new CSmain();

        Bukkit.broadcastMessage("Worked");
        event.getPlayer().teleport(mainClass.getSpawn());
        event.getPlayer().setGameMode(GameMode.ADVENTURE);

        setItem(event.getPlayer(), Material.COMPASS, "§2§kll §a§lGAMES §2§kll", 0);

}

I have tested it without creating the object (CSmain mainClass = new CSmain();) and the (event.getPlayer().teleport(mainClass.getSpawn());) and the Listener works fine. 我没有创建对象(CSmain mainClass = new CSmain();)和(event.getPlayer()。teleport(mainClass.getSpawn()))进行了测试,并且侦听器工作正常。 Whats wrong? 怎么了?

If that is your main mod class, you should never make a new instance of it. 如果那是您的主要mod类,则永远不要为其创建新实例。 Instead, you should have an 相反,您应该有一个

@Instance('yourmodid')
public static CSmain instance;

That way you can retrieve your mod instance from anywhere like so: 这样,您可以从任何地方检索您的mod实例,如下所示:

// assuming your getSpawn() returns chunk coordinates
ChunkCoordinates cc = CSmain.instance.getSpawn();

You can also get the world spawn position from event.entity.worldObj.getSpawn or getWorldSpawn - I can't remember off the top of my head and don't have code in front of me. 您还可以从event.entity.worldObj.getSpawn或getWorldSpawn获取世界生成位置-我不记得我的头并且没有代码在我面前。

EDIT: I see your spawn 'Location' field is both public and static, meaning you can access it directly: 编辑:我看到您的生成“位置”字段既是公共的又是静态的,这意味着您可以直接访问它:

CSmain.location;

I urge you to read up on what the static keyword means, as it can majorly affect your code in unexpected ways if you do not completely understand it. 我敦促您读一下static关键字的含义,因为如果您不完全理解它,它将以意想不到的方式极大地影响您的代码。 Please do not use it just so you can easily access a field. 请不要仅使用它,以便您可以轻松访问字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM