Script for generating ShadowCaster2Ds for Tilemaps

Hi everybody,

Since I did not find any built-in functionality to make shadow casters fit in the shape of the tilemaps (something that I think it is fundamental) I made my own script to achieve such thing without having to manually create and adjust every shadow caster.

Just add the script to your project and you will see a new option in the top menu of the editor. Once you execute it, shadow casters will be created for all the tilemaps in the open scene. It requires that the tilemaps have CompositeCollider2Ds. I made it as generic as possible so it is not limited to tilemaps, it only depends on composite colliders.

I hope it helps you to save some time.

I re-posted this on my website: Script for generating ShadowCaster2Ds for Tilemaps [Repost] - Jailbroken

Other code I shared:
Pixel perfect LineRenderer2D
Delaunay Triangulation with constrained edges
Target sorting layers as assets

Regards.

// Copyright 2020 Alejandro Villalba Avila
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;

/// <summary>
/// It extends the ShadowCaster2D class in order to be able to modify some private data members.
/// </summary>
public static class ShadowCaster2DExtensions
{
    /// <summary>
    /// Replaces the path that defines the shape of the shadow caster.
    /// </summary>
    /// <remarks>
    /// Calling this method will change the shape but not the mesh of the shadow caster. Call SetPathHash afterwards.
    /// </remarks>
    /// <param name="shadowCaster">The object to modify.</param>
    /// <param name="path">The new path to define the shape of the shadow caster.</param>
    public static void SetPath(this ShadowCaster2D shadowCaster, Vector3[] path)
    {
        FieldInfo shapeField = typeof(ShadowCaster2D).GetField("m_ShapePath",
                                                               BindingFlags.NonPublic |
                                                               BindingFlags.Instance);
        shapeField.SetValue(shadowCaster, path);
    }

    /// <summary>
    /// Replaces the hash key of the shadow caster, which produces an internal data rebuild.
    /// </summary>
    /// <remarks>
    /// A change in the shape of the shadow caster will not block the light, it has to be rebuilt using this function.
    /// </remarks>
    /// <param name="shadowCaster">The object to modify.</param>
    /// <param name="hash">The new hash key to store. It must be different from the previous key to produce the rebuild. You can use a random number.</param>
    public static void SetPathHash(this ShadowCaster2D shadowCaster, int hash)
    {
        FieldInfo hashField = typeof(ShadowCaster2D).GetField("m_ShapePathHash",
                                                              BindingFlags.NonPublic |
                                                              BindingFlags.Instance);
        hashField.SetValue(shadowCaster, hash);
    }
}

/// <summary>
/// It provides a way to automatically generate shadow casters that cover the shapes of composite colliders.
/// </summary>
/// <remarks>
/// Specially recommended for tilemaps, as there is no built-in tool that does this job at the moment.
/// </remarks>
public class ShadowCaster2DGenerator
{

#if UNITY_EDITOR

    [UnityEditor.MenuItem("Generate Shadow Casters", menuItem = "Tools/Generate Shadow Casters")]
    public static void GenerateShadowCasters()
    {
        CompositeCollider2D[] colliders = GameObject.FindObjectsOfType<CompositeCollider2D>();

        for(int i = 0; i < colliders.Length; ++i)
        {
            GenerateTilemapShadowCastersInEditor(colliders[i], false);
        }
    }

    [UnityEditor.MenuItem("Generate Shadow Casters (Self Shadows)", menuItem = "Tools/Generate Shadow Casters (Self Shadows)")]
    public static void GenerateShadowCastersSelfShadows()
    {
        CompositeCollider2D[] colliders = GameObject.FindObjectsOfType<CompositeCollider2D>();

        for (int i = 0; i < colliders.Length; ++i)
        {
            GenerateTilemapShadowCastersInEditor(colliders[i], true);
        }
    }

    /// <summary>
    /// Given a Composite Collider 2D, it replaces existing Shadow Caster 2Ds (children) with new Shadow Caster 2D objects whose
    /// shapes coincide with the paths of the collider.
    /// </summary>
    /// <remarks>
    /// It is recommended that the object that contains the collider component has a Composite Shadow Caster 2D too.
    /// It is recommended to call this method in editor only.
    /// </remarks>
    /// <param name="collider">The collider which will be the parent of the new shadow casters.</param>
    /// <param name="selfShadows">Whether the shadow casters will have the Self Shadows option enabled..</param>
    public static void GenerateTilemapShadowCastersInEditor(CompositeCollider2D collider, bool selfShadows)
    {
        GenerateTilemapShadowCasters(collider, selfShadows);

        UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
    }

#endif

    /// <summary>
    /// Given a Composite Collider 2D, it replaces existing Shadow Caster 2Ds (children) with new Shadow Caster 2D objects whose
    /// shapes coincide with the paths of the collider.
    /// </summary>
    /// <remarks>
    /// It is recommended that the object that contains the collider component has a Composite Shadow Caster 2D too.
    /// It is recommended to call this method in editor only.
    /// </remarks>
    /// <param name="collider">The collider which will be the parent of the new shadow casters.</param>
    /// <param name="selfShadows">Whether the shadow casters will have the Self Shadows option enabled..</param>
    public static void GenerateTilemapShadowCasters(CompositeCollider2D collider, bool selfShadows)
    {
        // First, it destroys the existing shadow casters
        ShadowCaster2D[] existingShadowCasters = collider.GetComponentsInChildren<ShadowCaster2D>();

        for (int i = 0; i < existingShadowCasters.Length; ++i)
        {
            if(existingShadowCasters[i].transform.parent != collider.transform)
            {
                continue;
            }

            GameObject.DestroyImmediate(existingShadowCasters[i].gameObject);
        }

        // Then it creates the new shadow casters, based on the paths of the composite collider
        int pathCount = collider.pathCount;
        List<Vector2> pointsInPath = new List<Vector2>();
        List<Vector3> pointsInPath3D = new List<Vector3>();

        for (int i = 0; i < pathCount; ++i)
        {
            collider.GetPath(i, pointsInPath);

            GameObject newShadowCaster = new GameObject("ShadowCaster2D");
            newShadowCaster.isStatic = true;
            newShadowCaster.transform.SetParent(collider.transform, false);

            for(int j = 0; j < pointsInPath.Count; ++j)
            {
                pointsInPath3D.Add(pointsInPath[j]);
            }

            ShadowCaster2D component = newShadowCaster.AddComponent<ShadowCaster2D>();
            component.SetPath(pointsInPath3D.ToArray());
            component.SetPathHash(Random.Range(int.MinValue, int.MaxValue)); // The hashing function GetShapePathHash could be copied from the LightUtility class
            component.selfShadows = selfShadows;
            component.Update();

            pointsInPath.Clear();
            pointsInPath3D.Clear();
        }
    }
}

If you want to generate it in runtime, on Awake, for a specific object:

// Copyright 2021 Alejandro Villalba Avila
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;

namespace Game.Utils
{
    /// <summary>
    /// Generates ShadowCaster2Ds for every continuous block of a tilemap on Awake, applying some settings.
    /// </summary>
    public class TilemapShadowCaster2D : MonoBehaviour
    {
        [SerializeField]
        protected CompositeCollider2D m_TilemapCollider;

        [SerializeField]
        protected bool m_SelfShadows = true;

        protected virtual void Reset()
        {
            m_TilemapCollider = GetComponent<CompositeCollider2D>();
        }

        protected virtual void Awake()
        {
            ShadowCaster2DGenerator.GenerateTilemapShadowCasters(m_TilemapCollider, m_SelfShadows);
        }
    }
}

If you need extra help to make it work in your project, you can read this instructions written by the user unity_23B1DCF752DC46F6F768
Script for generating ShadowCaster2Ds for Tilemaps page-2#post-8712126

25 Likes

You may want to add this to the general discussion here: The new 2D lighting on tilemaps, advice and suggestions?

How’s performance of this approach?

1 Like

Regarding performance, it only creates a GameObject with a ShaderCaster2D component per independent block (i.e. non-continuous block) of the Tilemap. For example, in the image, it creates 14 objects. I don’t know how the shadow casting system performs as the number of shadow casters increase, that’s my only doubt and nobody can do anything to solve that (apart from Unity guys). Besides, I don’t know if having a CompositeShadowCaster2D makes a difference or not in terms of performance.

1 Like

Wow, this is awesome!

Looks great, thank you.

Hi, the script works fine, but an error occurs when building the project, because Unity tries to add this script with UnityEditor to the build.

I solved this problem by adding the #if UNITY_EDITOR at the beginning and #endif at the end of the script.

Sorry I forgot to add the compiler definitions. I’ve updated the script.

1 Like

Wow, this actually worked unlike everything else I’ve tried so far! You’re a god!! I just hope there’s not too many side effects or performance intensive…

Quick addition for anyone trying to make this work : if you are using a Tilemap Collider 2D, you must add a Composite Collider 2D and check the “Used by Composite” option in the Tilemap Collider 2D for this to work. (You may also want to set the bodytype of the rigid body to static, if you don’t want your whole tilemap to fly)

Great work friend !

1 Like

Looks great!

The light travelled through walls for me, so I added the following code

component.selfShadows = true;

Hello,
I can’t seem to find the option that is supposed to execute. Could you send a screenshot or describe more specifically to me where I can find it? Sorry for this dumb question.

Edit:
I found it. It’s just me who had not searched properly. If someone else has the same issue that I had, here is how to access it.

Tools → Generate Shadow Casters

Yep, it’s that simple.
Again, sorry for this question.

2 Likes

Great! Thank you for the useful script.

Added the line “UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();”. Sometimes I just open the scene and generate the shadow casters, without making any other change. Since the editor does not realize about those changes, they are not saved. Pressing the Play button makes the scene restore its original content, as if nothing happened. Now the scenes are marked as dirty and everything works as expected.

Hello, does the script work on runtime

Never tried.

I’m pretty sure I got it to work at runtime in the past. You just have to remove anything that uses a “UnityEditor” namespace, like this line at the bottom:

UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();

Hi!

I can’t seem to get this to work.
If I understand correctly, all I need to do is

  1. Import Universal RP from Package Manager.
  2. Copy paste the script to somewhere in my project
  3. Create a Tilemap, (and edit the collisions of course).
  4. Add a Tilemap Collider 2D and Composite Collider 2D to the Tilemap. (Make sure to check “Used By Composite” under TileMap Collider 2D).
  5. Lastly, run Tools > Generate Shadow Casters.

Nothing changes after running it. I tested creating a new project for this but it made no difference.
I’m running Unity 2020.2.4f1

Is there anything obvious I’m missing?

Hi LordHobbas, let’s try to find the issue. I’m not sure but could it be related to the Geometry Type in the CompositeCollider2D?

Thanks for the quick response, I didn’t expect that!
It’s set to “Outlines”.
I can see now that there are several “ShadowCaster2D” created as children to the Tilemap object, and they’re recreated everytime I run the script. So the script seems to work perfectly. I think I’ve missed something else.
Do I need to enable something to make the Tilemap receive shadows as well?

You are welcome. If the shadow casters have the correct shape, then it all depends on the layers that are affected by the casters and the settings of the light, shadow intensity, target sorting layers, etc.