2017-03-09 93 views
0

枚舉我有以下枚舉文件 「DevelopmentCardType」:在創建一個新的DevelopmentCard插座事件ExceptionInInitializerError,使用在libGDX

enum DevelopmentCardType { 
    KNIGHT (0, new Texture(Gdx.files.internal("knight_card.png"))); 
    VICTORY_POINT (1, new Texture(Gdx.files.internal("victory_point_card.png"))), 

    private final Texture cardTexture; 
    private final int type; 
    private static final List<DevelopmentCardType> VALUES = Collections.unmodifiableList(Arrays.asList(values())); 

    DevelopmentCardType(int type, Texture cardTexture) { 
     this.type = type; 
     this.cardTexture = cardTexture; 
    } 

    public Texture getCardTexture() { 
     return cardTexture; 
    } 

    public static List<DevelopmentCardType> getVALUES() { 
     return VALUES; 
    } 
} 

「DevelopmentCard」 類:

class DevelopmentCard extends Card { 

    private float[] vertices = { 
     0, 0, 
     512, 0, 
     512, 512, 
     0, 512 
    }; 

    DevelopmentCard (int type) { 
    super(0, 0, 70, 100); 
    this.type = type; 
    createResourceCardSprite(type); 
    } 

    private void createResourceCardSprite(int resourceType) { 
    Texture cardTexture = DevelopmentCardType.getVALUES().get(resourceType).getCardTexture(); 
    TextureRegion textureRegion = new TextureRegion(cardTexture); 
    PolygonRegion polygonRegion = new PolygonRegion(textureRegion, vertices, new EarClippingTriangulator().computeTriangles(vertices).toArray()); 
    card = new PolygonSprite(polygonRegion); 
    } 
} 

當一個新的DevelopmentCard被創建時,它會創建一個ExceptionInInitializerError「,由於沒有OpenGL上下文。

這意味着在枚舉中使用的紋理還沒有創建,所以這就是爲什麼我想在第一次使用套接字事件時使用enum之前這樣做的原因。我可以通過在DevelopmentCardType類中添加一個init方法來解決這個問題,例如(我明白,在枚舉中調用任何方法(可能是這樣的一個空方法),而仍然在OpenGL上下文中可以解決問題,我不知道是否這是做正確的事):

static void init() {} 

,並調用這個類中的「主」之類DevelopmentCardType.init();

這是解決此問題的正確方法嗎?我還可以通過在OpenGL環境中創建DevelopmentCard來解決問題,然後創建新的DevelopmentCard實例不會導致錯誤。

回答

1

實例化紋理有兩個要求。它必須在GL線程上完成,並且必須在LibGDX初始化後完成。

第一次在任何地方引用DevelopmentCardType時,它將實例化它的所有值(KNIGHT和VICTORY_POINT)。這可能在Gdx引擎初始化之前發生(當您在DesktopLauncher或AndroidLauncher中調用初始化時會發生這種情況)。如果在Create()和render()方法之外的任何地方(例如構造函數或成員變量中)使用DevelopmentCardType,則它也可能發生在與GL線程不同的線程中。

此外,枚舉無法處理資源(紋理)的加載,這些資源是暫時性對象,當處理不當時會導致內存泄漏。

真的,您應該在一個地方處理您遊戲的所有資產,以便您輕鬆管理加載和卸載,並避免內存泄漏。 LibGDX已經有了一個強大的類來做這件事,AssetManager。如果你想保留一個類似於你當前代碼的結構,我建議用一個字符串替換你的枚舉的紋理成員,作爲紋理的文件名。這可以用來從AssetManager中檢索紋理。您可以將您的AssetManager實例傳遞給您的DevelopmentCard構造函數,以便它可以檢索紋理。

+0

我會看看如果我瞭解AssetManager,我會回到這個答案。 –

+0

所以我必須通過很多構造函數和DevelopmentCard和其他類的所有實例傳遞AssetManager實例?這不是很慢嗎?或者那是你的意思? –

+0

我已經實施了AssetManager,使用的內存已減半,現在我無需在使用它之前調用方法。謝謝 :) –