Skip to content

Instantly share code, notes, and snippets.

@MattRix
Last active February 2, 2022 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattRix/27db54d9e59d4aeb207583209ea27e12 to your computer and use it in GitHub Desktop.
Save MattRix/27db54d9e59d4aeb207583209ea27e12 to your computer and use it in GitHub Desktop.
Copy and paste sprite physics shapes between TextureImporter, SpriteRenderer and PolygonCollider2D using their context menus.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
public class SpriteShapeUtils
{
static List<Vector2>[] shapesByIndex = new List<Vector2>[0];
[MenuItem("CONTEXT/TextureImporter/Copy Physics Shape", priority = 110)]
static void CopyShapeFromImporter(MenuCommand command)
{
var importer = command.context as TextureImporter;
var sprite = AssetDatabase.LoadAssetAtPath<Sprite>(importer.assetPath);
CopyShapeFromSprite(sprite);
}
[MenuItem("CONTEXT/SpriteRenderer/Copy Physics Shape", priority = 110)]
static void CopyShapeFromSpriteRenderer(MenuCommand command)
{
var renderer = command.context as SpriteRenderer;
CopyShapeFromSprite(renderer.sprite);
}
[MenuItem("CONTEXT/PolygonCollider2D/Copy Physics Shape", priority = 110)]
static void CopyShapeFromCollider(MenuCommand command)
{
var collider = command.context as PolygonCollider2D;
shapesByIndex = new List<Vector2>[collider.pathCount];
for (int s = 0; s < shapesByIndex.Length; s++)
{
shapesByIndex[s] = new List<Vector2>(collider.GetPath(s));
}
}
[MenuItem("CONTEXT/PolygonCollider2D/Paste Physics Shape", priority = 110)]
static void PasteShapeIntoCollider(MenuCommand command)
{
var collider = command.context as PolygonCollider2D;
collider.pathCount = shapesByIndex.Length;
for (int s = 0; s < shapesByIndex.Length; s++)
{
collider.SetPath(s, shapesByIndex[s].ToArray());
}
}
[MenuItem("CONTEXT/PolygonCollider2D/Use Sprite Physics Shape", priority = 110)]
static void UseSpriteShape(MenuCommand command)
{
var collider = command.context as PolygonCollider2D;
//this checks for SpriteRenderer upwards through the hierarchy (starting at the current GameObject)
var sprite = collider.GetComponentInParent<SpriteRenderer>()?.sprite;
CopyShapeFromSprite(sprite);
PasteShapeIntoCollider(command);
}
private static void CopyShapeFromSprite(Sprite sprite)
{
if (sprite == null)
{
Debug.LogWarning("No Sprite found!");
return;
}
shapesByIndex = new List<Vector2>[sprite.GetPhysicsShapeCount()];
for (int s = 0; s < sprite.GetPhysicsShapeCount(); s++)
{
shapesByIndex[s] = new List<Vector2>();
sprite.GetPhysicsShape(s, shapesByIndex[s]);
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment