简体   繁体   中英

Libgdx java, Texture update method confusion

I have a method which changes a texture to another random one.

public void Texturechange(Texture texture){
        String imagename;
        randomImage = random.nextInt(90)+1;
         if ( randomImage <10){
                imagename="00"+ randomImage +".jpg";
            } else if(randomImage >9) {
                imagename="0"+ randomImage +".jpg";
            }
         Texture newTexture = new Texture(imagename);

         texture = newTexture;

    }

After printing the results I see texture changed to newTexture but it does not update on screen.However the following code does update on screen can anyone tell me why?

public void Texturechange(Texture texture){
            String imagename;
            randomImage = random.nextInt(90)+1;
             if ( randomImage <10){
                    imagename="00"+ randomImage +".jpg";
                } else if(randomImage >9) {
                    imagename="0"+ randomImage +".jpg";
                }

          Texture newTexture = new Texture(imagename);

          if(texture== theNameOfTextureInput){

         theNameOfTextureInput=newTexture;
         }





        }

Because Java is pass by value , changing the reference of the method parameter texture in the first case will not change the original reference that was passed to the method. In other words, assigning texture = newTexture; will not change the original texture that was passed by the caller of the method.

In the second case, you are assigning the newTexture to a field theNameOfTextureInput of the class (I'm saying it's a field because the variable is not declared in the method). You can change a field (assign a new reference to it) from any method as long as the method can access the field and the change will be reflected in the whole class (or object depending on whether the field is static or not).

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