-1

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, e.g. 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.

tygzy
  • 698
  • 1
  • 6
  • 23

2 Answers2

0

My suggestion would be to put everything that is in loadAssets() inside a static block if it has to be done only once, that is during initialisation phase.

Kavitha Karunakaran
  • 1,340
  • 1
  • 17
  • 32
0

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

deon cagadoes
  • 582
  • 2
  • 13