我有一种方法可以将纹理更改为另一个随机纹理。
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;
}
打印结果后,我看到纹理更改为 newTexture,但屏幕上没有更新。但是以下代码确实在屏幕上更新,有人可以告诉我为什么吗?
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;
}
}
最佳答案
因为Java是pass by value ,在第一种情况下更改方法参数 texture
的引用不会更改传递给该方法的原始引用。换句话说,分配texture = newTexture;
将不会更改方法调用者传递的原始texture
。
在第二种情况下,您将 newTexture
分配给类的字段 theNameOfTextureInput
(我说它是一个字段,因为该变量未在方法中声明)。您可以从任何方法更改字段(为其分配新的引用),只要该方法可以访问该字段,并且更改将反射(reflect)在整个类(或对象,具体取决于该字段是否静态)中。
关于java - Libgdx java,纹理更新方法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898395/