---
title: "JME3资源管理之三：资源加载流程"
author: "windybell"
date: "2015-08-28T17:41:26Z"
tags: []
categories: ["开源软件"]
slug: "jme3"
draft: false
lastmod: "2015-08-28T19:17:20Z"
id: 2238770
url: "https://windybell.iteye.com/blog/2238770"
---

系列目录：
[JME3资源管理之一：核心组件介绍](http://windybell.iteye.com/blog/2238630)
[JME3资源管理之二：AssetLoader和AssetLocator](http://windybell.iteye.com/blog/2238766)
[JME3资源管理之三：资源加载流程](http://windybell.iteye.com/blog/2238770)
[JME3资源管理之四：心得和小节](http://windybell.iteye.com/blog/2238799)

JME3在加载资源的过程中，AssetManager会先根据AssetKey去缓存中查找资源，如果找得到的话当然皆大欢喜，找不到的话才会去读取磁盘。

具体加载的流程是这样的：
**1、在缓存中查找资源**

检查AssetCache中的资源，若找不到就进行下一步，若找到就直接返回了。

```java
    AssetCache cache = handler.getCache(key.getCacheType());
    Object obj = cache != null ? cache.getFromCache(key) : null;
```


**2、匹配AssetLoader**

根据资源后缀名来匹配AssetLoader，找不到的话抛出异常。

```java
    AssetLoader loader = handler.aquireLoader(key);
```


**3、资源定位**

遍历所有注册过的AssetLocater，返回AssetInfo，找不到的话会抛出异常。

```java
    AssetInfo info = handler.tryLocate(key);
```


**4、加载资源**

调用AssetLoader的load(AssetInfo info)方法，返回资源对象。

```java
    obj = loader.load(info);
```


**5、后续处理**

AssetLoader返回Object类型的对象，经过AssetProcessor处理后，转换成实际的对象类型。
比如AWTLoader读取图片数据后，返回Image类型的对象。再通过TextureProcessor处理后才变成Texture对象。

```java
    AssetProcessor proc = handler.getProcessor(key.getProcessorType());
    if (proc != null){
        // do processing on asset before caching
        obj = proc.postProcess(key, obj);
    }
```


**6、保存到缓存**

资源加载结束后，对象会保存到缓存中。

```java
    if (cache != null){
        // At this point, obj should be of type T
        cache.addToCache(key, (T) obj);
    }
```