简体   繁体   中英

Java use var value from a different method that is called in a different class

Im making a game, and my problem is that I want to load all my assets in one method and that method be called in a different class.

This is my weapon loadAssets() method.

public void loadAssets() {
     BufferedImageLoader loader = new BufferedImageLoader();
     MP5Sprite = loader.loadImage("/img/weapons/Sprite001.png");

     SpriteSheet ss = new SpriteSheet(MP5Sprite);
     MP5Side = ss.grabImage(0, 0, 27, 10);
     MP5Top = ss.grabImage(32, 0, 3, 28);
}

These variables are declared at the start of my class, but values only made in this method.

I want to call this in my main game class, at the start when everything is loading like this.

for(int i = 0; i < com.main.engine.Handler.object.size(); i++) {
    GameObject tempObject = com.main.engine.Handler.object.get(i);
    tempObject.loadAssets();
}

This is how I am calling the method in my main game class, but because I'm not calling it in the weapon class it won't let me use those variables with the values I gave them, If it is not possible I can figure out another solution, but if it is that would be great.

I want to load everything at the start because of more images/sounds which before would only be loaded when the entity is added into the game/world, eg its assets are only loaded when that entity is spawned. As I would load all of the assets in the main method of each class.

我的建议是将 loadAssets() 中的所有内容放在静态块中,如果它只需要完成一次,那就是在初始化阶段。

Possible solution can be using this.localvariable here i make an example of your code:

public void loadAssets() {
     BufferedImageLoader loader = new BufferedImageLoader();
     this.MP5Sprite = loader.loadImage("/img/weapons/Sprite001.png");

     SpriteSheet ss = new SpriteSheet(this.MP5Sprite);
     this.MP5Side = ss.grabImage(0, 0, 27, 10);
     this.MP5Top = ss.grabImage(32, 0, 3, 28);
}

This can helpyou understand this : Difference between this.variable and variable in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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