The Svrf Unity Plugin
The Svrf SDK for Unity plugin starts by giving you access to the Svrf API, home to the largest search engine for augmented reality and virtual reality content. If you're looking to add face filters to your app, it also allows your users to stream ARKit and ARCore compatible 3D face filters.
To connect with the Svrf API, the Svrf SDK for Unity plugin utilizes the official Svrf C# library. You can use the class SvrfApi
to access the C# library's methods.
Looking for some help getting started? You can follow our recipe for Build a face filter app for Android with Unity and ARCore and it'll show you how to create a face filter app step-by-step.
C# Library
C# Library
The C# library can be used independently of the Svrf SDK for Unity. Parts of this guide include Unity specific references that may not apply to using the C# library independently.
The C# library can be used independently of the Svrf SDK for Unity. If you'd like to use the C# library independently, you can install it using NuGet.
Installation of the Svrf SDK
Installing on Unity
Download the package
Download the latest Svrf.unitypackage
from the releases page.
Import the Svrf package
- Open Unity and create a new 3D project.
- Select Assets > Import Package > Custom Package.
- Select the
Svrf.unitypackage
file that you downloaded. - In the Importing Package dialog, click Import.
For more information about importing packages in Unity, see the Importing custom Asset packages section in Unity docs.
Installation with NuGet
Installation via NuGet is the preferable way. You can install it by searching for Svrf
package in the NuGet window or by typing the following command into the Package Manager console:
Install-Package Svrf
Manual installation
If you don't want to use NuGet, you can download svrf-dlls.zip
from our releases page. Then unzip the downloaded file and use Svrf.dll
in your project.
Newtonsoft.Json dependency
Our library depends on Newtonsoft.Json package. All dependencies are handled automatically when installing via NuGet, but if you add Svrf.dll manually, it has to be in the same folder with the Newtonsoft.Json.dll.
Authenticate Your App
Authenticating a Unity App
If you are using the Svrf SDK for Unity Plugin, you can authenticate two different ways: using a game object or in a script.
Runtime Integration
We recommend using the Svrf SDK for Unity as a runtime integration. This will allow your users to search and access all of the content from Svrf while using your app.
Providing the Svrf API key in a GameObject
- Right click on your scene and in the menu, select Svrf > Api Key.
- In the Inspector window, enter your Svrf API key in the Api Key field.
If you don't want to create an extra GameObject you can attach SvrfApiKey.cs
script to any existing GameObject.
Making Runtime Requests
With the Svrf API, you can requests and load AR/VR media at runtime. Doing so can help minimize your application's size and allow your users access a ever growing library of content.
To use the Svrf API at runtime, set the static property of the SvrfApiKey
class.
using Svrf.Unity;SvrfApiKey.Value = /* Add your Svrf API Key here */;
Authenticating the C# Library
You can use the C# library independently, but it requires a different authentication method.
Before you make your first request, you have to create a new instance of the SvrfClient class and provide your Svrf API Key.
using Svrf;SvrfClient svrf = new SvrfClient("Add your Svrf API Key here");
The library will automatically handle authenticating your Svrf API Key, attaching your Authentication Token to your requests' headers, and renew expired tokens. Optionally, you can set up the library to require manual authentication.
Authentication tokens will be automatically saved in memory while your app is running. Optionally, you can provide your own custom token storage methods.
Making API Requests
There are three methods to fetch content from the Svrf API. There's search, that allows your users to enter a query and get back related results. Then there's trending, which provides your users with access to curated immersive content. If you know exactly which piece of content the user needs, you can also get media directly by its id.
Making API Requests in Unity
The plugin provides a SvrfApi
class. It is inherited from SvrfClient
class from the Svrf C# library. You can use the same methods provided in Svrf's C# library to make API requests to Svrf.
Making API Requests in Unity
The Svrf SDK for Unity uses the Svrf C# library to make requests.
Providing your Svrf API Key for Authentication in Unity
You do not have to provide your Svrf API key as a constructor argument. Set your Svrf API key using the `SvrfAPIKey.Value`. See Authenticating Your App to learn more about authentication.
using System.Linq;using Svrf;using Svrf.Models.Http;using Svrf.Models.Media;using Svrf.Unity;SvrfApiKey.Value = /* Add your Svrf API Key here */;SvrfApi api = new SvrfApi();MediaRequestParams requestOptions = new MediaRequestParams { IsFaceFilter = true };MultipleMediaResponse trendingResponse = await api.Media.GetTrendingAsync(requestOptions);MediaModel model = trendingResponse.Media.First();
Setting Request Options
You can set the request options for search and trending requests.
The Svrf library offers enum support so you don't have to remember our enums values for categories, stereoscopic types, and media types. You can find them in the Svrf.Models.Enums
namespace.
using System.Collections.Generic;using Svrf.Models.Enums;using Svrf.Models.Http;MediaRequestParams requestOptions = new MediaRequestParams { Type = new[] { MediaType.Photo } };MultipleMediaResponse response = await svrf.Media.GetTrendingAsync(requestOptions);IEnumerable<MediaModel> photos = response.Media;
Let's walk through all of the request options that you can set in the MediaRequestParams
instance.
Category Category?
Retrieve a specific category of Media.
HasBlendShapes bool?
Request 3D Media that has or does not have blend shapes.
IsFaceFilter bool?
Set to true
to retrieve only face filter 3D Media.
MinimumWidth int?
Deprecated
360 photos and 360 videos are no longer supported on Svrf.
PageNum int?
To fetch the next page of search results, use the NextPageNum
returned from the previous page in the PageNum
option value.
RequiresBlendShapes bool?
3D models, specifically face filters, that require blend shapes are best experienced when blend shape animations are active. We strongly suggest that any 3D models where RequiresBlendShapes
is true
must incorporate blend shape animations in their application to ensure the user has a high-quality experience.
If you'd like to use face filters without blend shapes, we strongly urge you to set this option to false
.
Using Face Filters Without Blend Shapes
If you'd like to use face filters without blend shapes, we strongly urge you to set RequiresBlendShapes to false.
Size int?
To adjust the quantity of Media returned, adjust the Size
option. Requests are limited to 100 Media per request.
StereoscopicType StereoscopicType?
Deprecated
Stereoscopic 360 photos and 360 videos are no longer supported on Svrf.
Type IEnumerable<MediaType>
In the request options, you can set the type
options to a collection of the MediaType
enum: Model3D
, Photo
, and Video
, or you can omit it to get all types of media.
Deprecated
360 photos and 360 videos are no longer supported on Svrf.
Search
The svrf.Media.SearchAsync
method brings the power of immersive search found on Svrf.com to your app or project. Svrf's search engine enables your users to instantly find the immersive experience they're seeking. Content is sorted by the Svrf rating system, ensuring that the highest quality content and most prevalent search results are returned.
using System.Collections.Generic;using Svrf.Models.Http;using Svrf.Models.Media;const string query = "cats";MultipleMediaResponse response = await svrf.Media.SearchAsync(query);IEnumerable<MediaModel> cats = response.Media; // You've got the cats.
Get Trending
The svrf.Media.GetTrendingAsync
provides your app or project with the hottest immersive content. The experiences returned mirror Svrf, from timely cultural content to trending pop-culture references. The trending experiences are updated regularly by human curators to ensure users always get fresh updates of immersive content.
using System.Collections.Generic;using Svrf.Models.Http;using Svrf.Models.Media;MultipleMediaResponse response = await svrf.Media.GetTrendingAsync();IEnumerable<MediaModel> trendingMedia = response.Media;
Pagination
Fetching the next page of results can be done by setting the PageNum
option for search and trending requests.
using System.Collections.Generic;using Svrf.Models.Http;int nextPageNum;MultipleMediaResponse firstResponse = await svrf.Media.GetTrendingAsync();nextPageNum = firstResponse.NextPageNum;MediaRequestParams options = new MediaRequestParams { PageNum = nextPageNum };MultipleMediaResponse secondResponse = await svrf.Media.GetTrendingAsync(options);
Get Media
To get a specific piece of media from Svrf by ID, use the svrf.Media.GetByIdAsync
method.
In this example, we're fetching Media with ID 547963
.
using System.Collections.Generic;using Svrf.Models.Http;using Svrf.Models.Media;SingleMediaResponse response = await svrf.Media.GetByIdAsync(547963);IEnumerable<MediaModel> media = response.Media;
Running async operations as coroutines
As you have noticed, all methods of our API are async. That means they must be used with the await
keyword. However, if you want to use coroutines, you can use our extension method .AsCoroutine()
that transforms the .NET Task
into a Unity coroutine that you can use.
using System.Collections;using System.Linq;using Svrf.Models.Http;using Svrf.Models.Media;using Svrf.Unity.Coroutines;using UnityEngine;public IEnumerator Start(){SvrfApi api = new SvrfApi();TaskBasedCoroutine<MultipleMediaResponse> requestCoroutine = api.Media.GetTrendingAsync().AsCoroutine();yield return requestCoroutine;MediaModel model = requestCoroutine.Result.Media.First();yield return SvrfModel.GetSvrfModelAsync(model).AsCoroutine();}
Running async operations synchronously
We strongly recommend using operations asynchronously. However, if you need to perform a request synchronously, you can use the following approach:
using System.Collections.Generic;using System.Threading.Tasks;using Svrf.Models.Http;using Svrf.Models.Media;Task<MultipleMediaResponse> getTrendingTask = svrf.Media.GetTrendingAsync();MultipleMediaResponse response = getTrendingTask.Result; // Blocks thread until async request is finished.IEnumerable<MediaModel> media = response.Media;
Loading 3D Models in Unity
Adding a SvrfModel Component Using the Editor
This method is best used when you know exactly which model you want to add to your experience.
Rendering at Runtime
We recommend using the Svrf SDK for Unity as a runtime integration. This will allow your users to search and access all of the content from Svrf while using your app.
- Right click on your scene and select Svrf > 3D Model.
- In the Inspector window, provide a Svrf Model Id for the 3D model that you would like to include.
Svrf Asset Viewer in Unity
You can find a model's ID using the built-in Svrf Asset Viewer
Check if a model has loaded
SvrfModel component has an IsLoading
property. You can check it in your code, for example in the Update
method.
using Svrf.Unity;using UnityEngine;void Update(){// Let's assume this script is attached to the Svrf model game object.// If it's another script, you have to use GameObject.Find() method// or pass the model game object as the script property.SvrfModel svrfModel = gameObject.GetComponent<SvrfModel>();if (!svrfModel.IsLoading){// The loading is finished. You can remove your loading indicator// or perform any other logic.Destroy(loadingSpinner);enabled = false;}}
Loading a 3D Model at Runtime
SvrfModel
component has static function GetSvrfModelAsync()
. It can be used to render a 3D model in your Unity application at runtime.
The function is asynchronous and returns Task<GameObject>
where GameObject
instance is a newly created GameObject
or the GameObject
that you provided as the 3rd argument.
using System.Linq;using Svrf.Models.Http;using Svrf.Models.Media;using Svrf.Unity.Models;using UnityEngine;SvrfApi api = new SvrfApi();MediaRequestParams requestOptions = new MediaRequestParams {IsFaceFilter = true};MultipleMediaResponse trendingResponse = await api.Media.GetTrendingAsync(requestOptions);MediaModel model = trendingResponse.Media.First();SvrfModelOptions options = new SvrfModelOptions{ShaderOverride = Shader.Find("Svrf/LightEstimation"),WithOccluder = true,};GameObject svrfModel = await SvrfModel.GetSvrfModelAsync(model, options);
Check if a model has loaded in run-time
It's super easy in the run-time since you call and await the GetSvrfModelAsync yourself.
using System.Linq;using Svrf.Models.Http;using Svrf.Models.Media;using UnityEngine;SvrfApi api = new SvrfApi();MediaRequestParams requestOptions = new MediaRequestParams {IsFaceFilter = true};MultipleMediaResponse trendingResponse = await api.Media.GetTrendingAsync(requestOptions);MediaModel model = trendingResponse.Media.First();GameObject svrfModel = await SvrfModel.GetSvrfModelAsync(model);// The loading is finished. You can remove your loading indicator// or perform any other logic.Destroy(loadingSpinner);
Advanced Options for 3D Models
Remove the Default Occluder
You can optionally use or remove the occlusion geometry (aka occluder) that is provided with the model by default. Removing the occluder allows you to use a face filter without one or with your own custom occluder.
To remove the occluder, set WithOccluder
to false
in your script or uncheck the With Occluder checkbox in the Inspector window.
using System.Linq;using Svrf.Models.Http;using Svrf.Models.Media;using Svrf.Unity.Models;using UnityEngine;SvrfApi api = new SvrfApi();MediaRequestParams requestOptions = new MediaRequestParams {IsFaceFilter = true};MultipleMediaResponse trendingResponse = await api.Media.GetTrendingAsync(requestOptions);MediaModel model = trendingResponse.Media.First();SvrfModelOptions options = new SvrfModelOptions {WithOccluder = false};GameObject svrfModel = await SvrfModel.GetSvrfModelAsync(model, options);
Apply Custom Shaders
The Svrf SDK for Unity, allows you to apply a custom shader to a loaded model.
Custom Shaders in the Editor
To add a custom shader in the Editor, apply your custom shader using the Inspector window and applying it in the *Shader Override field.
Custom Shaders at Runtime
You can also provide a custom shader in your script to render at runtime.
using System.Linq;using Svrf.Models.Http;using Svrf.Models.Media;using Svrf.Unity.Models;using UnityEngine;SvrfApi api = new SvrfApi();MediaRequestParams requestOptions = new MediaRequestParams {IsFaceFilter = true};MultipleMediaResponse trendingResponse = await api.Media.GetTrendingAsync(requestOptions);MediaModel model = trendingResponse.Media.First();SvrfModelOptions modelOptions = new SvrfModelOptions {ShaderOverride = Shader.Find("CustomShader")};await SvrfModel.GetSvrfModelAsync(model, modelOptions);
Unity Asset Viewer
If you're looking for specific assets to add to your application, we've create an asset viewer that you can access from the Unity editor. The Svrf Asset Viewer allows you to search for 3D models from the Svrf API and see a preview. You can select any model from the preview and add it to your app.
You can select to limit the results to only face filter 3D models. Leaving the search input empty will return trending 3D models. The viewer can be pinned to panels just like any other Unity window.
Opening from the main menu (creating new GameObject)
You can open the window from the menu by selecting Window>Svrf. When clicking a preview, a new GameObject with the model will be created.
Adding new game objects
When accessing the Svrf Asset Viewer through the menu, every click on a preview image generates a new *GameObject*.
Opening from the SvrfModel script (changing a GameObject)
Svrf Model script has the Open Svrf Window button. Clicking on a preview image will modify the existing GameObject from your script.
Adding new game objects
When accessing the Svrf Asset Viewer through a script, clicking on a preview image will modify the existing *GameObject* from your script.
Advanced Unity Settings
When initializing a new instance of the Svrf library, you have the option to set advanced options.
using Svrf;using Svrf.Models;ApiOptions options = new ApiOptions{// Set advanced options};SvrfClient svrf = new SvrfClient("Add your Svrf API Key here", options);
Manual Authentication
When you create a new Svrf instance, the library will automatically authenticate your Svrf API Key.
However, you may want to postpone the initial authentication request and manually control when the Svrf API Key is authenticated. In that case, you can set IsManualAuthentication
option to true
. Then call svrf.AuthenticateAsync()
manually whenever you want.
code": "using Svrf;using Svrf.Models;using Svrf.Models.Media;ApiOptions options = new ApiOptions { IsManualAuthentication = true };SvrfClient svrf = new SvrfClient("Add your Svrf API Key here", options);// Let's say we know that user is IDLE// and we have time to make an auth request.await svrf.AuthenticateAsync();MediaModel trendingMedia = (await svrf.Media.GetTrendingAsync()).Media;
Custom Token Storage
Authentication tokens will be automatically saved in memory. Optionally, you can provide your own custom token storage methods using the ApiOptions.Storage
property. Provided storage should implement ITokenStorage
interface.
using Svrf.Models;using Svrf.Storage;public class CustomTokenStorage : ITokenStorage{public AppTokenInfo Get(){return YourCustomStorage.Read();}public void Set(AppTokenInfo appTokenInfo){return YourCustomStorage.Write(appTokenInfo);}public void Clear(){return YourCustomStorage.Clear();}}
using Svrf;using Svrf.Models;CustomTokenStorage customStorage = new CustomTokenStorage();ApiOptions options = new ApiOptions { Storage = customStorage };SvrfClient svrf = new SvrfClient("Add your Svrf API Key here", options);