# webGL Template

**URL:** <https://discussions.unity.com/t/webgl-template/602637>\
**Category:** Build Automation\
**Tags:** Unity-Build-Automation, Question\
**Created:** [October 23, 2015, 3:31pm UTC](https://discussions.unity.com/t/webgl-template/602637 "2015-10-23T15:31:51Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Riolis](https://avatars.discourse-cdn.com/v4/letter/r/b2d939/32.png) [@Riolis](https://discussions.unity.com/u/Riolis)\
**Post date:** [October 23, 2015, 3:31pm UTC](https://discussions.unity.com/t/webgl-template/602637/1 "2015-10-23T15:31:51Z")

</div>

It seems like the cloud build doesn’t use my selected template for building, and I can’t seem find the setting for it to select it anywhere.

Would be great if someone knows how to set this up could advice me. Else I would have to move tons of html and js code to jslib or eval it at the start scene which is not fun thing to do.

Thanks.

---

<div class="post-metadata">

**Author:** ![dannyd](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/dannyd/32/99396_2.png) [@dannyd](https://discussions.unity.com/u/dannyd)\
**Post date:** [October 23, 2015, 4:07pm UTC](https://discussions.unity.com/t/webgl-template/602637/2 "2015-10-23T16:07:23Z")

</div>

This is not something we plan to support at the moment. We always build with the default template so that we can host the html properly and so the styling is consistent with the rest of our site, and the window sizing acts correctly. If your project requires more complex interaction with the page, unfortunately your only real option is to self host builds.

Thinking about how this might work in the future - what kinds of things are you doing in your template?

---

<div class="post-metadata">

**Author:** ![Riolis](https://avatars.discourse-cdn.com/v4/letter/r/b2d939/32.png) [@Riolis](https://discussions.unity.com/u/Riolis)\
**Post date:** [October 23, 2015, 4:58pm UTC](https://discussions.unity.com/t/webgl-template/602637/3 "2015-10-23T16:58:50Z")

</div>

nothing fancy, just some bootstrap modal and input=“file” forms since you can’t seem to trigger it from unity itself (Being block by all browsers popup blocker by default), large file upload/download script, drag and drop file js event, [parse.com](http://parse.com) js sdk and its custom helper script currently.

In a nutshell we are experimenting with more of a commercial cms type of system rather then games (and to see how far we can go with it, and hoping to make a better user experience), which unfortunately needs more interaction with the pages.

---

<div class="post-metadata">

**Author:** ![jinxed\_byte](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/jinxed_byte/32/433857_2.png) [@jinxed\_byte](https://discussions.unity.com/u/jinxed_byte)\
**Post date:** [December 17, 2015, 11:33am UTC](https://discussions.unity.com/t/webgl-template/602637/4 "2015-12-17T11:33:04Z")

</div>

We would also like to select a WebGL template and connect to the javascript code. Especially, we are working on integration of [Parse.com](http://Parse.com) and PeerJS.

Hope you can make the template available soon.

---

<div class="post-metadata">

**Author:** ![samurai926](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/samurai926/32/526580_2.png) [@samurai926](https://discussions.unity.com/u/samurai926)\
**Post date:** [March 2, 2017, 2:48am UTC](https://discussions.unity.com/t/webgl-template/602637/5 "2017-03-02T02:48:59Z")

</div>

+1 for option to use custom template during cloudbuild. Ours has a custom loading script and expands the canvas to full screen.

---

<div class="post-metadata">

**Author:** ![Kmausser](https://avatars.discourse-cdn.com/v4/letter/k/e19b73/32.png) [@Kmausser](https://discussions.unity.com/u/Kmausser)\
**Post date:** [June 2, 2017, 5:08pm UTC](https://discussions.unity.com/t/webgl-template/602637/6 "2017-06-02T17:08:18Z")

</div>

Why aren’t custom templates supported yet?

---

<div class="post-metadata">

**Author:** ![PlayItSafe\_Fries](https://avatars.discourse-cdn.com/v4/letter/p/8797f3/32.png) [@PlayItSafe\_Fries](https://discussions.unity.com/u/PlayItSafe_Fries)\
**Post date:** [January 24, 2018, 4:07pm UTC](https://discussions.unity.com/t/webgl-template/602637/7 "2018-01-24T16:07:56Z")

</div>

After looking for a solution online but still getting nowhere, I decided to look into writing a workaround myself.

Just put this code anywhere in your project (Preferrably under an /Editor folder) and don’t forget to replace the part with your actual template name.

Although this solution works for now, I still hope Unity will remove this limitation and let developers make the full use of their cloud build system.

```csharp
#if UNITY_EDITOR && UNITY_WEBGL
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Callbacks;
using UnityEditor;
using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Linq;

public class PostProcessWebGL
{
    //The name of the WebGLTemplate. Location in project should be Assets/WebGLTemplates/<YOUR TEMPLATE NAME>
    const string __TemplateToUse = "<YOUR TEMPLATE NAME>";

    [PostProcessBuild]
    public static void ChangeWebGLTemplate(BuildTarget buildTarget, string pathToBuiltProject)
    {
        if (buildTarget != BuildTarget.WebGL) return;

        //create template path
        var templatePath = Paths.Combine(Application.dataPath, "WebGLTemplates", __TemplateToUse);

        //Clear the TemplateData folder, built by Unity.
        FileUtilExtended.CreateOrCleanDirectory(Paths.Combine(pathToBuiltProject, "TemplateData"));

        //Copy contents from WebGLTemplate. Ignore all .meta files
        FileUtilExtended.CopyDirectoryFiltered(templatePath, pathToBuiltProject, true, @".*/\.+|\.meta$", true);

        //Replace contents of index.html
        FixIndexHtml(pathToBuiltProject);
    }

    //Replaces %...% defines in index.html
    static void FixIndexHtml(string pathToBuiltProject)
    {
        //Fetch filenames to be referenced in index.html
        string
            webglBuildUrl,
            webglLoaderUrl;
     
        if (File.Exists(Paths.Combine(pathToBuiltProject, "Build", "UnityLoader.js")))
        {
            webglLoaderUrl = "Build/UnityLoader.js";
        }
        else
        {
            webglLoaderUrl = "Build/UnityLoader.min.js";
        }

        string buildName = pathToBuiltProject.Substring(pathToBuiltProject.LastIndexOf("/") + 1);
        webglBuildUrl = string.Format("Build/{0}.json", buildName);

        //webglLoaderUrl = EditorUserBuildSettings.development? "Build/UnityLoader.js": "Build/UnityLoader.min.js";
        Dictionary<string, string> replaceKeywordsMap = new Dictionary<string, string> {
                {
                    "%UNITY_WIDTH%",
                    PlayerSettings.defaultWebScreenWidth.ToString()
                },
                {
                    "%UNITY_HEIGHT%",
                    PlayerSettings.defaultWebScreenHeight.ToString()
                },
                {
                    "%UNITY_WEB_NAME%",
                    PlayerSettings.productName
                },
                {
                    "%UNITY_WEBGL_LOADER_URL%",
                    webglLoaderUrl
                },
                {
                    "%UNITY_WEBGL_BUILD_URL%",
                    webglBuildUrl
                }
            };

        string indexFilePath = Paths.Combine(pathToBuiltProject, "index.html");
       Func<string, KeyValuePair<string, string>, string> replaceFunction = (current, replace) => current.Replace(replace.Key, replace.Value);
        if (File.Exists(indexFilePath))
        {
           File.WriteAllText(indexFilePath, replaceKeywordsMap.Aggregate<KeyValuePair<string, string>, string>(File.ReadAllText(indexFilePath), replaceFunction));
        }

    }

    private class FileUtilExtended
    {
     
        internal static void CreateOrCleanDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                Directory.Delete(dir, true);
            }
            Directory.CreateDirectory(dir);
        }

        //Fix forward slashes on other platforms than windows
        internal static string FixForwardSlashes(string unityPath)
        {
            return ((Application.platform != RuntimePlatform.WindowsEditor) ? unityPath : unityPath.Replace("/", @"\"));
        }

        //Copies the contents of one directory to another.
       public static void CopyDirectoryFiltered(string source, string target, bool overwrite, string regExExcludeFilter, bool recursive)
        {
            RegexMatcher excluder = new RegexMatcher()
            {
                exclude = null
            };
            try
            {
                if (regExExcludeFilter != null)
                {
                    excluder.exclude = new Regex(regExExcludeFilter);
                }
            }
            catch (ArgumentException)
            {
               UnityEngine.Debug.Log("CopyDirectoryRecursive: Pattern '" + regExExcludeFilter + "' is not a correct Regular Expression. Not excluding any files.");
                return;
            }
            CopyDirectoryFiltered(source, target, overwrite, excluder.CheckInclude, recursive);
        }
       internal static void CopyDirectoryFiltered(string sourceDir, string targetDir, bool overwrite, Func<string, bool> filtercallback, bool recursive)
        {
            // Create directory if needed
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
                overwrite = false;
            }

            // Iterate all files, files that match filter are copied.
            foreach (string filepath in Directory.GetFiles(sourceDir))
            {
                if (filtercallback(filepath))
                {
                    string fileName = Path.GetFileName(filepath);
                    string to = Path.Combine(targetDir, fileName);

                 
                    File.Copy(FixForwardSlashes(filepath),FixForwardSlashes(to), overwrite);
                }
            }

            // Go into sub directories
            if (recursive)
            {
                foreach (string subdirectorypath in Directory.GetDirectories(sourceDir))
                {
                    if (filtercallback(subdirectorypath))
                    {
                        string directoryName = Path.GetFileName(subdirectorypath);
                       CopyDirectoryFiltered(Path.Combine(sourceDir, directoryName), Path.Combine(targetDir, directoryName), overwrite, filtercallback, recursive);
                    }
                }
            }
        }

        internal struct RegexMatcher
        {
            public Regex exclude;
            public bool CheckInclude(string s)
            {
                return exclude == null || !exclude.IsMatch(s);
            }
        }

    }

    private class Paths
    {
        //Combine multiple paths using Path.Combine
        public static string Combine(params string[] components)
        {
            if (components.Length < 1)
            {
                throw new ArgumentException("At least one component must be provided!");
            }
            string str = components[0];
            for (int i = 1; i < components.Length; i++)
            {
                str = Path.Combine(str, components[i]);
            }
            return str;
        }
    }

}

#endif

```

Good luck!

---

<div class="post-metadata">

**Author:** ![StaffanEk](https://avatars.discourse-cdn.com/v4/letter/s/df788c/32.png) [@StaffanEk](https://discussions.unity.com/u/StaffanEk)\
**Post date:** [January 25, 2018, 9:31am UTC](https://discussions.unity.com/t/webgl-template/602637/8 "2018-01-25T09:31:55Z")

</div>

> [@dannyd](#):
>
> We always build with the default template so that we can host the html properly and so the styling is consistent with the rest of our site, and the window sizing acts correctly.

What are you talking about? I don’t want you to host my WebGL build, I want you to build it. It’s called Cloud Build not Cloud Host. What a ridiculous excuse.

What the hell am I paying for?

---

<div class="post-metadata">

**Author:** ![PlayItSafe\_Fries](https://avatars.discourse-cdn.com/v4/letter/p/8797f3/32.png) [@PlayItSafe\_Fries](https://discussions.unity.com/u/PlayItSafe_Fries)\
**Post date:** [January 25, 2018, 11:08am UTC](https://discussions.unity.com/t/webgl-template/602637/9 "2018-01-25T11:08:00Z")

</div>

> [@StaffanEk](#):
>
> What are you talking about? I don’t want you to host my WebGL build, I want you to build it. It’s called Cloud Build not Cloud Host. What a ridiculous excuse.
> 
> What the hell am I paying for?

Exactly.  
I don’t see why anyone would want to host their game on Unity using the default template.  
While cloud build is supposed to make a developer’s life easier (quote: “Cloud Build - Build games faster”) It’s actually giving us more work because we’d have to:

- Press “Start Cloud Build”

- Wait 35 minutes for Unity to build the project.

- download and unzip the generated build

- replace the templatedata folder and index.html with the correct one

- Upload the contents to our ftp

- Hope that we didn’t break anything and that we won’t have to go back to 1.

Anyway, right now we finally managed to fully automate our our build pipeline for WebGL and Android:  
After cloud build, Unity will notify a webhook I have set up, running in Azure, which will download and extract the .zip file and then upload it to our own FTP.

---

<div class="post-metadata">

**Author:** ![Ponytech](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/ponytech/32/103970_2.png) [@Ponytech](https://discussions.unity.com/u/Ponytech)\
**Post date:** [February 13, 2018, 1:01pm UTC](https://discussions.unity.com/t/webgl-template/602637/10 "2018-02-13T13:01:35Z")

</div>

> [@dannyd](#):
>
> We always build with the default template so that we can host the html properly and so the styling is consistent with the rest of our site, and the window sizing acts correctly. If your project requires more complex interaction with the page, unfortunately your only real option is to self host builds.
> 
> Thinking about how this might work in the future - what kinds of things are you doing in your template?

Seriously? This makes either cloud build or custom templates useless.  
We use Cloud Build for building our WebGL version and webhooks to download and deploy the game on our own servers once the build is complete. Please remove this limitation.

---

<div class="post-metadata">

**Author:** ![Ponytech](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/ponytech/32/103970_2.png) [@Ponytech](https://discussions.unity.com/u/Ponytech)\
**Post date:** [April 26, 2018, 8:16am UTC](https://discussions.unity.com/t/webgl-template/602637/11 "2018-04-26T08:16:43Z")

</div>

As forums are not the good place to complain about missing features I created an issue on Unity Feedback :

[https://feedback.unity3d.com/suggestions/webgl-cloud-build-should-support-cusom-templates](https://feedback.unity3d.com/suggestions/webgl-cloud-build-should-support-cusom-templates)

Please vote for it 🙂

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/system/32/97283_2.png) [@system](https://discussions.unity.com/u/system)\
**Post date:** [May 10, 2018, 2:54am UTC](https://discussions.unity.com/t/webgl-template/602637/12 "2018-05-10T02:54:57Z")

</div>

There was another one already

[https://feedback.unity3d.com/suggestions/allow-building-with-webgltemplates-instead-of-just-the-default](https://feedback.unity3d.com/suggestions/allow-building-with-webgltemplates-instead-of-just-the-default)

---

<div class="post-metadata">

**Author:** ![Ponytech](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/ponytech/32/103970_2.png) [@Ponytech](https://discussions.unity.com/u/Ponytech)\
**Post date:** [May 10, 2018, 6:54am UTC](https://discussions.unity.com/t/webgl-template/602637/13 "2018-05-10T06:54:16Z")

</div>

> [@](#):
>
> There was another one already
> 
> [https://feedback.unity3d.com/suggestions/allow-building-with-webgltemplates-instead-of-just-the-default](https://feedback.unity3d.com/suggestions/allow-building-with-webgltemplates-instead-of-just-the-default)

Damn, I didn’t see it even though I made a search. Thanks your reporting it, and let’s gather votes on the older one.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/system/32/97283_2.png) [@system](https://discussions.unity.com/u/system)\
**Post date:** [May 10, 2018, 3:23pm UTC](https://discussions.unity.com/t/webgl-template/602637/14 "2018-05-10T15:23:09Z")

</div>

> [@Ponytech](#):
>
> Damn, I didn’t see it even though I made a search. Thanks your reporting it, and let’s gather votes on the older one.

I didn’t see it either, at first, but I noticed I had ten new votes available (problem with unity feedback is I run out of votes quickly!) and started browsing through all the issues…

---

<div class="post-metadata">

**Author:** ![pravusjif](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/pravusjif/32/334107_2.png) [@pravusjif](https://discussions.unity.com/u/pravusjif)\
**Post date:** [October 26, 2018, 8:13pm UTC](https://discussions.unity.com/t/webgl-template/602637/15 "2018-10-26T20:13:29Z")

</div>

> [@PlayItSafe\_Fries](#):
>
> ```csharp
> #if UNITY_EDITOR && UNITY_WEBGL
> using System.Collections.Generic;
> using UnityEngine;
> using UnityEditor.Callbacks;
> using UnityEditor;
> using System.IO;
> using System;
> using System.Text.RegularExpressions;
> using System.Linq;
> 
> public class PostProcessWebGL
> {
> //The name of the WebGLTemplate. Location in project should be Assets/WebGLTemplates/<YOUR TEMPLATE NAME>
> const string __TemplateToUse = "<YOUR TEMPLATE NAME>";
> 
> [PostProcessBuild]
> public static void ChangeWebGLTemplate(BuildTarget buildTarget, string pathToBuiltProject)
> {
> if (buildTarget != BuildTarget.WebGL) return;
> 
> //create template path
> var templatePath = Paths.Combine(Application.dataPath, "WebGLTemplates", __TemplateToUse);
> 
> //Clear the TemplateData folder, built by Unity.
> FileUtilExtended.CreateOrCleanDirectory(Paths.Combine(pathToBuiltProject, "TemplateData"));
> 
> //Copy contents from WebGLTemplate. Ignore all .meta files
> FileUtilExtended.CopyDirectoryFiltered(templatePath, pathToBuiltProject, true, @".*/\.+|\.meta$", true);
> 
> //Replace contents of index.html
> FixIndexHtml(pathToBuiltProject);
> }
> 
> //Replaces %...% defines in index.html
> static void FixIndexHtml(string pathToBuiltProject)
> {
> //Fetch filenames to be referenced in index.html
> string
> webglBuildUrl,
> webglLoaderUrl;
>     
> if (File.Exists(Paths.Combine(pathToBuiltProject, "Build", "UnityLoader.js")))
> {
> webglLoaderUrl = "Build/UnityLoader.js";
> }
> else
> {
> webglLoaderUrl = "Build/UnityLoader.min.js";
> }
> 
> string buildName = pathToBuiltProject.Substring(pathToBuiltProject.LastIndexOf("/") + 1);
> webglBuildUrl = string.Format("Build/{0}.json", buildName);
> 
> //webglLoaderUrl = EditorUserBuildSettings.development? "Build/UnityLoader.js": "Build/UnityLoader.min.js";
> Dictionary<string, string> replaceKeywordsMap = new Dictionary<string, string> {
> {
> "%UNITY_WIDTH%",
> PlayerSettings.defaultWebScreenWidth.ToString()
> },
> {
> "%UNITY_HEIGHT%",
> PlayerSettings.defaultWebScreenHeight.ToString()
> },
> {
> "%UNITY_WEB_NAME%",
> PlayerSettings.productName
> },
> {
> "%UNITY_WEBGL_LOADER_URL%",
> webglLoaderUrl
> },
> {
> "%UNITY_WEBGL_BUILD_URL%",
> webglBuildUrl
> }
> };
> 
> string indexFilePath = Paths.Combine(pathToBuiltProject, "index.html");
> Func<string, KeyValuePair<string, string>, string> replaceFunction = (current, replace) => current.Replace(replace.Key, replace.Value);
> if (File.Exists(indexFilePath))
> {
> File.WriteAllText(indexFilePath, replaceKeywordsMap.Aggregate<KeyValuePair<string, string>, string>(File.ReadAllText(indexFilePath), replaceFunction));
> }
> 
> }
> 
> private class FileUtilExtended
> {
>     
> internal static void CreateOrCleanDirectory(string dir)
> {
> if (Directory.Exists(dir))
> {
> Directory.Delete(dir, true);
> }
> Directory.CreateDirectory(dir);
> }
> 
> //Fix forward slashes on other platforms than windows
> internal static string FixForwardSlashes(string unityPath)
> {
> return ((Application.platform != RuntimePlatform.WindowsEditor) ? unityPath : unityPath.Replace("/", @"\"));
> }
> 
> //Copies the contents of one directory to another.
> public static void CopyDirectoryFiltered(string source, string target, bool overwrite, string regExExcludeFilter, bool recursive)
> {
> RegexMatcher excluder = new RegexMatcher()
> {
> exclude = null
> };
> try
> {
> if (regExExcludeFilter != null)
> {
> excluder.exclude = new Regex(regExExcludeFilter);
> }
> }
> catch (ArgumentException)
> {
> UnityEngine.Debug.Log("CopyDirectoryRecursive: Pattern '" + regExExcludeFilter + "' is not a correct Regular Expression. Not excluding any files.");
> return;
> }
> CopyDirectoryFiltered(source, target, overwrite, excluder.CheckInclude, recursive);
> }
> internal static void CopyDirectoryFiltered(string sourceDir, string targetDir, bool overwrite, Func<string, bool> filtercallback, bool recursive)
> {
> // Create directory if needed
> if (!Directory.Exists(targetDir))
> {
> Directory.CreateDirectory(targetDir);
> overwrite = false;
> }
> 
> // Iterate all files, files that match filter are copied.
> foreach (string filepath in Directory.GetFiles(sourceDir))
> {
> if (filtercallback(filepath))
> {
> string fileName = Path.GetFileName(filepath);
> string to = Path.Combine(targetDir, fileName);
> 
>                 
> File.Copy(FixForwardSlashes(filepath),FixForwardSlashes(to), overwrite);
> }
> }
> 
> // Go into sub directories
> if (recursive)
> {
> foreach (string subdirectorypath in Directory.GetDirectories(sourceDir))
> {
> if (filtercallback(subdirectorypath))
> {
> string directoryName = Path.GetFileName(subdirectorypath);
> CopyDirectoryFiltered(Path.Combine(sourceDir, directoryName), Path.Combine(targetDir, directoryName), overwrite, filtercallback, recursive);
> }
> }
> }
> }
> 
> internal struct RegexMatcher
> {
> public Regex exclude;
> public bool CheckInclude(string s)
> {
> return exclude == null || !exclude.IsMatch(s);
> }
> }
> 
> }
> 
> private class Paths
> {
> //Combine multiple paths using Path.Combine
> public static string Combine(params string[] components)
> {
> if (components.Length < 1)
> {
> throw new ArgumentException("At least one component must be provided!");
> }
> string str = components[0];
> for (int i = 1; i < components.Length; i++)
> {
> str = Path.Combine(str, components[i]);
> }
> return str;
> }
> }
> 
> }
> 
> #endif
> 
> ```

Thanks a lot for this! it seems to be the only workaround for now.

---

<div class="post-metadata">

**Author:** ![bourriquet](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/bourriquet/32/1029216_2.png) [@bourriquet](https://discussions.unity.com/u/bourriquet)\
**Post date:** [January 15, 2019, 6:07pm UTC](https://discussions.unity.com/t/webgl-template/602637/16 "2019-01-15T18:07:02Z")

</div>

Thanks @PlayItSafe_Fries for your code!  
I modified it a bit to make it more generic.  
Now the Custom Template is automatically taken from your build settings.  
Also, if it’s not using a custom template, we don’t do anything (as built-in templates don’t have issues).  
Also, I made the regex to filter based on the local path only. I use Jenkins, and all this happens in a “.jenkins” folder, so every file was filtered out because of the parent hidden folder.  
So here is the new version:

```csharp
#if UNITY_EDITOR && UNITY_WEBGL
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Callbacks;
using UnityEditor;
using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Linq;

public class PostProcessWebGL
{

    const string CUSTOM_TEMPLATE_PREFIX = "PROJECT:";

    static bool __UsesCustomTemplate { get { return PlayerSettings.WebGL.template.StartsWith(CUSTOM_TEMPLATE_PREFIX); } }

    static string __CustomTemplateName { get { return PlayerSettings.WebGL.template.Substring(CUSTOM_TEMPLATE_PREFIX.Length); } }

    static string __CustomTemplatePath { get { return Paths.Combine(Application.dataPath, "WebGLTemplates",__CustomTemplateName); } }

    [PostProcessBuild]
    public static void ChangeWebGLTemplate(BuildTarget buildTarget, string pathToBuiltProject)
    {
        if (buildTarget != BuildTarget.WebGL) return;

        if (!__UsesCustomTemplate) return;

        Debug.Log("Add Custom WebGL Template: " + __CustomTemplateName);

        //Clear the TemplateData folder, built by Unity.
        FileUtilExtended.CreateOrCleanDirectory(Paths.Combine(pathToBuiltProject, "TemplateData"));

        //Copy contents from WebGLTemplate. Ignore all .meta files
        FileUtilExtended.CopyDirectoryFiltered(__CustomTemplatePath, pathToBuiltProject, true, @".*/\.+|\.meta$", true);

        //Replace contents of index.html
        FixIndexHtml(pathToBuiltProject);
    }

    //Replaces %...% defines in index.html
    static void FixIndexHtml(string pathToBuiltProject)
    {
        //Fetch filenames to be referenced in index.html
        string
            webglBuildUrl,
            webglLoaderUrl;

        if (File.Exists(Paths.Combine(pathToBuiltProject, "Build", "UnityLoader.js")))
        {
            webglLoaderUrl = "Build/UnityLoader.js";
        }
        else
        {
            webglLoaderUrl = "Build/UnityLoader.min.js";
        }

        string buildName = pathToBuiltProject.Substring(pathToBuiltProject.LastIndexOf("/") + 1);
        webglBuildUrl = string.Format("Build/{0}.json", buildName);

        //webglLoaderUrl = EditorUserBuildSettings.development? "Build/UnityLoader.js": "Build/UnityLoader.min.js";
        Dictionary<string, string> replaceKeywordsMap = new Dictionary<string, string> {
                    {
                        "%UNITY_WIDTH%",
                        PlayerSettings.defaultWebScreenWidth.ToString()
                    },
                    {
                        "%UNITY_HEIGHT%",
                        PlayerSettings.defaultWebScreenHeight.ToString()
                    },
                    {
                        "%UNITY_WEB_NAME%",
                        PlayerSettings.productName
                    },
                    {
                        "%UNITY_WEBGL_LOADER_URL%",
                        webglLoaderUrl
                    },
                    {
                        "%UNITY_WEBGL_BUILD_URL%",
                        webglBuildUrl
                    }
                };

        string indexFilePath = Paths.Combine(pathToBuiltProject, "index.html");
        Func<string, KeyValuePair<string, string>, string> replaceFunction = (current, replace) => current.Replace(replace.Key, replace.Value);
        if (File.Exists(indexFilePath))
        {
            File.WriteAllText(indexFilePath, replaceKeywordsMap.Aggregate<KeyValuePair<string, string>, string>(File.ReadAllText(indexFilePath), replaceFunction));
        }

    }

    private class FileUtilExtended
    {

        internal static void CreateOrCleanDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                Directory.Delete(dir, true);
            }
            Directory.CreateDirectory(dir);
        }

        //Fix forward slashes on other platforms than windows
        internal static string FixForwardSlashes(string unityPath)
        {
            return ((Application.platform != RuntimePlatform.WindowsEditor) ? unityPath : unityPath.Replace("/", @"\"));
        }

        //Copies the contents of one directory to another.
        public static void CopyDirectoryFiltered(string source, string target, bool overwrite, string regExExcludeFilter, bool recursive)
        {
            RegexMatcher excluder = new RegexMatcher()
            {
                exclude = null
            };
            try
            {
                if (regExExcludeFilter != null)
                {
                    excluder.exclude = new Regex(regExExcludeFilter);
                }
            }
            catch (ArgumentException)
            {
                UnityEngine.Debug.Log("CopyDirectoryRecursive: Pattern '" + regExExcludeFilter + "' is not a correct Regular Expression. Not excluding any files.");
                return;
            }
            CopyDirectoryFiltered(source, target, overwrite, excluder.CheckInclude, recursive);
        }
        internal static void CopyDirectoryFiltered(string sourceDir, string targetDir, bool overwrite, Func<string, bool> filtercallback, bool recursive)
        {
            // Create directory if needed
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
                overwrite = false;
            }

            // Iterate all files, files that match filter are copied.
            foreach (string filepath in Directory.GetFiles(sourceDir))
            {
                string localPath = filepath.Substring(sourceDir.Length);
                if (filtercallback(localPath))
                {
                    string fileName = Path.GetFileName(filepath);
                    string to = Path.Combine(targetDir, fileName);

                    File.Copy(FixForwardSlashes(filepath), FixForwardSlashes(to), overwrite);
                }
            }

            // Go into sub directories
            if (recursive)
            {
                foreach (string subdirectorypath in Directory.GetDirectories(sourceDir))
                {
                    string localPath = subdirectorypath.Substring(sourceDir.Length);
                    if (filtercallback(localPath))
                    {
                        string directoryName = Path.GetFileName(subdirectorypath);
                        CopyDirectoryFiltered(Path.Combine(sourceDir, directoryName), Path.Combine(targetDir, directoryName), overwrite, filtercallback, recursive);
                    }
                }
            }
        }

        internal struct RegexMatcher
        {
            public Regex exclude;
            public bool CheckInclude(string s)
            {
                return exclude == null || !exclude.IsMatch(s);
            }
        }

    }

    private class Paths
    {
        //Combine multiple paths using Path.Combine
        public static string Combine(params string[] components)
        {
            if (components.Length < 1)
            {
                throw new ArgumentException("At least one component must be provided!");
            }
            string str = components[0];
            for (int i = 1; i < components.Length; i++)
            {
                str = Path.Combine(str, components[i]);
            }
            return str;
        }
    }

}

#endif

```

---

<div class="post-metadata">

**Author:** ![MaxGuernseyIII](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/maxguernseyiii/32/44245_2.png) [@MaxGuernseyIII](https://discussions.unity.com/u/MaxGuernseyIII)\
**Post date:** [June 2, 2019, 4:50pm UTC](https://discussions.unity.com/t/webgl-template/602637/17 "2019-06-02T16:50:09Z")

</div>

> [@bourriquet](#):
>
> I modified it a bit to make it more generic.

In Unity Cloud Build, it seems that PostProcessBuildAttribute cannot be used.

It builds locally, but not on UCB.

Is anyone else having this experience?

---

<div class="post-metadata">

**Author:** ![NeoSu](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/neosu/32/515907_2.png) [@NeoSu](https://discussions.unity.com/u/NeoSu)\
**Post date:** [April 29, 2020, 6:25am UTC](https://discussions.unity.com/t/webgl-template/602637/18 "2020-04-29T06:25:54Z")

</div>

hmm…it’s 2020 and the webGL cloud build still cannot use a custom template. I guess I’ll have to build my 20 webGL html on my own laptop?

---

<div class="post-metadata">

**Author:** ![MaxGuernseyIII](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/maxguernseyiii/32/44245_2.png) [@MaxGuernseyIII](https://discussions.unity.com/u/MaxGuernseyIII)\
**Post date:** [May 13, 2020, 11:02am UTC](https://discussions.unity.com/t/webgl-template/602637/19 "2020-05-13T11:02:53Z")

</div>

You can theoretically do a Unity build in Azure DevOps. I’ve had a lot more luck managing my own build server than using a hosted agent. The Android tools won’t work without a manual install step. The Mac stuff, of course, doesn’t work.

Also, a $150 piece of hardware seems to completely run circles around Unity Cloud Build and is pretty fast when compared with Azure DevOps hosted agents.

WebGL and Windows standalone seem to be the only builds people are reliably getting to work on Azure DevOps… so you may be in luck, if you choose that route.

---

<div class="post-metadata">

**Author:** ![colinsenner](https://avatars.discourse-cdn.com/v4/letter/c/c2a13f/32.png) [@colinsenner](https://discussions.unity.com/u/colinsenner)\
**Post date:** [November 10, 2020, 12:52am UTC](https://discussions.unity.com/t/webgl-template/602637/20 "2020-11-10T00:52:29Z")

</div>

Since this thread was so helpful to me recently I wanted to contribute. I wrote a blog post on how I solved this issue with the above code since some of the function signatures seem to have changed and I wanted a solution that didn’t rely on the [PostProcessBuild] attribute but rather on my Unity Cloud configuation settings.

Big thanks to @PlayItSafe_Fries and @bourriquet in the thread. It’s still insane we can’t use Custom WebGL templates with Unity Cloud Build, when they’re already well supported by Unity.

**TLDR for my blog post:**

The function signature for a “Post-Export Method” is

```csharp
public static void func(string)

```

This should come as no big surprise, but when I was trying to solve this I ran into trying to use the solutions by other users’ function signatures, which don’t work if you’re doing it via configuration options.

@bourriquet 's code doesn’t work anymore because when Unity Cloud builds the project it sets

```csharp
PlayerSettings.WebGL.template = "Application:smile:efault"

```

instead of what it does locally and his solution relys on:

```csharp
PlayerSettings.WebGL.template = "PROJECT:CustomTemplate"

```

Here’s the full info for how I got it all working with Unity 2019.2.x recently.

> **[Unity Cloud Build with custom template](https://colinsenner.com/blog/unity-cloud-build-with-custom-template/)**
>
> A Seattle-based design studio. Focused on 3D artwork, product visualization, VR/AR experiences, technical artwork, and consulting.

Hope this helps!  
Colin

[Next page](https://discussions.unity.com/t/webgl-template/602637.md?page=2)
