How to configure Needle Engine with SvelteKit to load assets from root when routing changes?

I’m integrating Needle Engine into a SvelteKit project and ran into a routing issue:

When I navigate to a nested route like /path1 or /path2, Needle tries to load assets from a relative path like /path1/assets/ instead of from /assets/ at the root.

This causes asset loading to fail when accessing routes directly or refreshing the page.

Is there a recommended way to configure Needle Engine or the project build so that all assets (e.g. glb, textures) are always loaded from the root path (i.e. /assets/...), regardless of the current route?

I’m currently using the SvelteKit static adapter.

needle.config.json

{
  "baseUrl": "assets",
  "buildDirectory": "build",
  "assetsDirectory": "static/assets",
  "scriptsDirectory": "src/lib/scripts",
  "codegenDirectory": "src/lib/generated"
}

Hi oot4chi, the simplest solution is to set your assets base path as an absolute URL. Right now your config uses a relative path (“assets”), which means that when you’re on a nested route the browser will resolve it relative to that route (e.g. “/path1/assets”). To fix this, update your needle.config.json so that the baseUrl includes a leading slash (“/assets”):

{
  "baseUrl": "/assets",
  "buildDirectory": "build",
  "assetsDirectory": "static/assets",
  "scriptsDirectory": "src/lib/scripts",
  "codegenDirectory": "src/lib/generated"
}

This tells Needle Engine to always load assets from the root, regardless of the current route in your SvelteKit project. After making this change, rebuild your project and the assets (glb, textures, etc.) should load correctly in all routes.

For more details on how Needle Engine uses the baseUrl setting, you can refer to the documentation and the Needle config examples (see at needle-engine-unity—NeedleProjectConfig.cs.txt).

1 replies left - Become PRO for more replies.
thread_sTpzgBB2X0OJ23GYZp7QTTMK
Reply to this post directly if you need further help (bottom right button)

Hi, Needle Engine by itself doesnt load assets or route asset paths - this sounds like a configuration issue in your Sveltekit project.

Especially look for example at these files:

which is slotted into the src attribute

You can modify the template to your liking and handle routing differently - it’s just an example for all means and purposes.

I’ll try doing it this use globalThis[“needle:codegen_files”].

<script lang="ts">
  import { onMount } from "svelte";
  import { base } from "$app/paths";

  let src: string | undefined = $state(undefined);

  onMount(async () => {
    await import("@needle-tools/engine");
    await import("../generated/gen.js");
    src = `${base}/${globalThis["needle:codegen_files"]}`;
  });

</script>

<needle-engine {src}></needle-engine>

This topic was automatically closed 13 days after the last reply. New replies are no longer allowed.