Skip to content

Instantly share code, notes, and snippets.

@Invertex
Created January 22, 2023 10:54
Show Gist options
  • Save Invertex/15e76cd0909164d6eea67e8b31112c8b to your computer and use it in GitHub Desktop.
Save Invertex/15e76cd0909164d6eea67e8b31112c8b to your computer and use it in GitHub Desktop.
Extension methods for modify the PhysicsMaterial2D on Rigidbody2D/Collider2D components without it affecting other objects.
using UnityEngine;
namespace Invertex.Unity2D.Physics
{
public static class Physics2DExtensions
{
//Example Usage: rigidbody.ModifyUniquePhysicsMaterial2D(0.5f, 0.2f);
/// <summary>
/// Sets the given values on the PhysicsMaterial2D of the Rigidbody. If a material unique to this object doesn't exist, a new one will be created just for it.
/// </summary>
/// <param name="rb">The target Rigidbody to change the Physics Material 2D of.</param>
/// <param name="bounciness">Modify Bounciness. Default value less than 0 will result in existing value being kept.</param>
/// <param name="friction">Modify Friction. Default value less than 0 will result in existing value being kept.</param>
public static void ModifyUniquePhysicsMaterial2D(this Rigidbody2D rb, float bounciness = -1, float friction = -1) => rb.sharedMaterial = ModifyUniquePhysicsMaterial2D(rb.sharedMaterial, rb, bounciness, friction);
/// <summary>
/// Sets the given values on the PhysicsMaterial2D of the Rigidbody. If a material unique to this object doesn't exist, a new one will be created just for it.
/// </summary>
/// <param name="col">The target Collider2D to change the Physics Material 2D of.</param>
/// <param name="bounciness">Modify Bounciness. Default value less than 0 will result in existing value being kept.</param>
/// <param name="friction">Modify Friction. Default value less than 0 will result in existing value being kept.</param>
public static void ModifyUniquePhysicsMaterial2D(this Collider2D col, float bounciness = -1, float friction = -1) => col.sharedMaterial = ModifyUniquePhysicsMaterial2D(col.sharedMaterial, col, bounciness, friction);
private static PhysicsMaterial2D ModifyUniquePhysicsMaterial2D(PhysicsMaterial2D curMat, Object target, float bounciness = -1, float friction = -1)
{
//Only replace the values if they're valid/non-default
bounciness = bounciness < 0 ? curMat.bounciness : bounciness;
friction = friction < 0 ? curMat.friction : friction;
//Instance a Unique copy if one isn't already assigned, so we don't modify all objects sharing the material
var instID = target.GetInstanceID().ToString();
if (curMat.name != instID)
{ //Avoid instantiating a new material everytime we modify the same object again
curMat = new PhysicsMaterial2D(instID); //
}
curMat.bounciness = bounciness;
curMat.friction = friction;
return curMat;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment