ResourceService

This is a service that provides various functions for resources.

# Methods

[{"index":"void ClearCaches()","0":"Removes all loaded resources from the cache. To free resources from memory, first clear the cache with the ClearCaches() function and then use the UnloadUnusedResources() function."}]

[{"index":"ResourceType GetTypeAndWait(string RUID) (Yield)","0":"Returns the resource type for the RUID."}]

[{"index":"AnimationClip LoadAnimationClipAndWait(string RUID) (Yield)","0":"Loads an animation clip resource. Loaded resources are cached, and they will be stored in memory to be reused when needed. Stops script execution while performing."}]

[{"index":"Sprite LoadSpriteAndWait(string RUID) (Yield)","0":"Loads the sprite resource. Loaded resources are cached, and they will be stored in memory to be reused when needed. Stops script execution while performing."}]

[{"index":"void PreloadAsync(List ruidList, func> completeCallback)","0":"Pre-loads an RUID selected from the ruidList. Loaded resources are cached and not deleted from the memory for reuse as necessary. This is executed asynchronously. When the operation is complete, the function delivered to completeCallback will be called, and the load result will be returned in the same order of the resource RUID set to ruidList."}]

[{"index":"void PreloadTileSetAsync(string tileSetId, func completeCallback)","0":"Pre-loads all Sprite resources in the tile set. The tileSetId is the Id of the TileDataSet entries. This is executed asynchronously. When the operation is complete, the function delivered to completeCallback will be called, and the load result will be returned."}]

[{"index":"void RemoveCaches(List ruidList)","0":"Removes loaded resources from the cache. ruidList is the RUID of the resources to be removed. To free resources from memory, first use this function to clear the cache, then use the UnloadUnusedResources function."}]

[{"index":"void RequestSpriteUploadAsync(RawImage rawImage, func callbackFunction) (ClientOnly)","0":"Converts RawImage into a sprite, uploads it to the server, and gets an RUID. The first parameter of callbackFunction is the error code, and the second is the issued RUID."}]

[{"index":"void SetSpriteUploadValidationCallback(func -> boolean callbackFunction) (ServerOnly)","0":"Registers a function that determines whether to allow resource uploads when requested by a client. Returns true if the request is granted, false otherwise."}]

[{"index":"void UnloadUnusedResources(float pendingTimeSeconds)","0":"Frees resources from memory. Resources eligible for release are any resources that have not been used for pendingTimeSeconds and have been removed from the cache. The time units are in seconds."}]

##### inherited from Service:

[{"index":"EventHandlerBase ConnectEvent(string key, IScriptFunction eventHandler)","0":"Links events. When a key-type event occurs in this service, a handler is notified. The handler receives event parameters."}]

[{"index":"EventHandlerBase ConnectEvent(Type eventType, IScriptFunction eventHandler)","0":"Links events. This service notifies a handler when an eventType event occurs. The handler receives event parameters."}]

[{"index":"boolean DisconnectEvent(string key, EventHandlerBase eventHandler)","0":"Disconnects the event with the key-type event and the handler."}]

[{"index":"boolean DisconnectEvent(Type eventType, EventHandlerBase eventHandler)","0":"Disconnects the eventType event from its handler."}]

[{"index":"void SendEvent(EventType sendEvent)","0":"Generates an event."}]

# Events

[{"index":"ResourceUploadEvent","0":"This event is raised in ResourceService when a resource created during world play is uploaded. This event will fire on every server in the world where the resource was uploaded."}]

# Examples

#### PreloadAsync

This is an example of loading a list of resources using the `PreloadAsync()` function and showing a loading screen while loading resources. The `ShowLoadingScreen()` and `HideLoadingScreen()` function definitions have been omitted.
    
    
    @Component
    script AssetPreloadScreen extends Component
        @ExecSpace("ClientOnly")
        method void ResourceLoadWithLoadingScreen()
        -- Shows the loading screen to the user. 
        self:ShowLoadingScreen()
    
        -- List of resources to load.
        local ruids = {
        	"6d1a308b27164b02921d812b05c78cba",
        	 "0516d7594a394561893e04de713cfb6a",
        	 "ce55606c96d94c059227f2956a1ae786",
        	 "b64e41d2e3774276aa7db7bdb74410b9",
        	 "df9ce4abd6e24a619e72e6f592a28ce7"
        }
    
        -- Starts loading the resource list. Once the load is complete, a callback is executed that hides the loading screen.
        _ResourceService:PreloadAsync(ruids, function()
    
         -- Hides the loading screen. 
         	self:HideLoadingScreen()
        end)
        end
    end
    

#### SetSpriteUploadValidationCallback

This is an example of creating a screenshot as a sprite resource and uploading it using `ResourceService`. When a user uploads a screenshot, you must first create a function that allows uploading. The upload acceptance decision function must be registered when the world is created and should be maintained continuously, so it should be written as a function in Logic. Since the decision to allow an upload is made on the server, function registration must also be done on the server. This example checks whether the user has permission to upload and decides whether to allow it.
    
    
    @Component
    script SpriteUploadValidator extends Component
        @ExecSpace("ServerOnly")
        method void OnBeginPlay()
        -- Registers a callback to determine whether to allow sprite upload.
        _ResourceService:SetSpriteUploadValidationCallback(self.ValidateSpriteUpload)
        end
    
        @ExecSpace("ServerOnly")
        method boolean ValidateSpriteUpload(string userId)
        if self:IsAuthorizedUser(userId) == false then
        -- Blocks sprite upload.
        	return false
        end
    
        -- Allows sprite upload.
        return true
        end
    end
    

The client takes a screenshot using `ScreenshotService`, converts it into data, and uploads it through `ResourceService` to create a sprite resource.
    
    
    @Component
    script ScreenshotSpriteCreator extends Component
        @ExecSpace("ClientOnly")
        method void CaptureScreenshotAndUpload()
        -- Takes screenshots and turns them into data.
        local screenshotError, pixelData = _ScreenshotService:CaptureFullScreenAsPixelDataAndWait()
    
        -- Checks if an error occurred while taking a screenshot.
        if screenshotError ~= ScreenshotError.Success then
        	log_error("Failed to capture screenshot. error: " .. tostring(screenshotError))
        	return
        end
    
        -- Uploads screenshot data and turns it into a sprite resource.
        -- When the upload is complete, the OnScreenshotUploaded function specified as a callback is called.
        _ResourceService:RequestSpriteUploadAsync(pixelData, self.OnScreenshotUploaded)
        end
    
        @ExecSpace("ClientOnly")
        method void OnScreenshotUploaded(any resourceUploadError, string ruid)
        -- Checks if an error occurred during the screenshot upload process.
        if resourceUploadError ~= ResourceUploadError.Success then
         	log_error("Failed to upload screenshot. error: " .. tostring(resourceUploadError))
        	return
        end
    
        -- If the upload is successful, you will receive the RUID of the sprite resource created from the screenshot.
        -- Checks the sprite by assigning the received RUID to SpriteRendererComponent.
        self.Entity.SpriteRendererComponent.SpriteRUID = ruid
        end
    end
    

`ResourceUploadEvent` occurs in `ResourceService` when resource upload is successful. You can use `ResourceUploadEvent` to specify what to do on the server when uploading a resource. Please note that `ResourceUploadEvent` occurs on all servers in the world where the resource was uploaded. In this example, the RUID of the uploaded resource and the ID of the user who uploaded it are recorded so that they can be used in future plays. In situations like the example, you need to check whether the user corresponding to the `UserId` is connected to this server to prevent duplicate records from multiple servers.
    
    
    @Component
    script ResourceUploadRecorder extends Component
        @EventSender("Service", "ResourceService")
        handler HandleResourceUploadEvent(ResourceUploadEvent event)
        -- Parameters
        local RUID = event.RUID
        local UserId = event.UserId
        --------------------------------------------------------
    
        -- This event occurs on the server when resource upload is successful.
        	local userEntity = _UserService:GetUserEntityByUserId(UserId)
    
        if _EntityService:IsValid(userEntity) then
        	self:RecordUploadedResource(RUID, UserId)
        end
        end
    end
    

#### GetTypeAndWait

This is an example of checking the resource type.
    
    
    @Component
    script AssetTypeInitializer extends Component
        method void OnBeginPlay()
        -- sprite
        local type = _ResourceService:GetTypeAndWait('f55cd1b715c14593a97caff8b147d544')
        log(type)
    
        -- animationclip
        local type2 = _ResourceService:GetTypeAndWait('235ede11f6a24ecb85f6271833d06ba0')
        log(type2)
        end
    end
    

#### RemoveCaches

This is an example of removing old resources and loading necessary resources.
    
    
    @Component
    script SkillTransitionManager extends Component
        @ExecSpace("ClientOnly")
        method void UpgradeSkill(string id)
        -- Calls functions responsible for removing and adding skills.
        self:RemoveSkill(self.currentId)
        self.currentId = id
        self:AddSkill(self.currentId)
    
        local oldRuids = self.currentRuids
        -- Releases resources used in previous skills from the cache.
        _ResourceService:RemoveCaches(oldRuids)
    
        -- Frees uncached and unused resources from memory.
        _ResourceService:UnloadUnusedResources(0)
    
        -- Brings a list of resources to load.
        local newRuids = self:GetRuids(id)
    
        self.currentRuids = newRuids
        self.currentId = id
    
        -- Starts loading the resource list. Once loading is complete, it calls a function responsible for further actions.
        _ResourceService:PreloadAsync(newRuids, function()
        	self:AfterLoadSkillResource()
        end)
        end
    
        @ExecSpace("ClientOnly")
        method table GetRuids(string id)
        -- Initializes ruids information if it has not been initialized.
        if self.cachedRuidsById == nil then
        	self:InitializeRuids()
        end
    
        local ruids = self.cachedRuidsById[id]
        return ruids
        end
    end
    

#### ClearCaches

This is an example of clearing the cache of all cached resources when navigating to the lobby map.
    
    
    @Component
    script LobbyMapCacheCleaner extends Component
        @ExecSpace("ClientOnly")
        method void BeforeMoveLobbyMap()
        -- Releases all cached resources from the cache.
        _ResourceService:ClearCaches()
    
        -- When moving between maps, UnloadUnusedResources() is automatically called internally.
        -- _ResourceService:UnloadUnusedResources(0)
        end
    end
    

# SeeAlso

  * SpriteRendererComponent
  * DataStorageService
  * ScreenshotService
  * [Screenshots and Dynamic Sprites](/docs?postId=829)