Is there a way to show all colliders 2D in a a released game at once? I am making a 2D game in Unity and have to show all colliders to the player. Can I use Gizmos?
1 Answer
Gizmos are only visible in the Editor, so that is not a solution.
Instead, you can render the colliders or (simulate rendering them) any number of ways.
BoxCollider2D
If your 2D colliders are boxes, this is pretty simple -- use a LineRenderer
to render the collider's outline.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class DrawBoxCollider2D : MonoBehaviour
{
[SerializeField] private GameObject linePrefab;
LineRenderer lineRenderer;
BoxCollider2D boxCollider2D;
void Start()
{
lineRenderer = Instantiate(linePrefab).GetComponent<LineRenderer>();
lineRenderer.transform.SetParent(transform);
lineRenderer.transform.localPosition = Vector3.zero;
boxCollider2D = GetComponent<BoxCollider2D>();
}
void Update()
{
HiliteBox();
}
void HiliteBox()
{
Vector3[] positions = new Vector3[4];
positions[0] = transform.TransformPoint( new Vector3(boxCollider2D.size.x / 2.0f, boxCollider2D.size.y / 2.0f,0));
positions[1] = transform.TransformPoint(new Vector3(-boxCollider2D.size.x / 2.0f, boxCollider2D.size.y / 2.0f,0));
positions[2] = transform.TransformPoint(new Vector3(-boxCollider2D.size.x / 2.0f, -boxCollider2D.size.y / 2.0f,0));
positions[3] = transform.TransformPoint(new Vector3(boxCollider2D.size.x / 2.0f, -boxCollider2D.size.y / 2.0f,0));
lineRenderer.SetPositions(positions);
}
}
Here's the set up to get this to work:
PolygonCollider 2D
Polygon colliders are only a little more complex. They can consist of several paths (to allow for holes); to make the code easy to follow and sheer expediency, my example will make the dumb assumption that there is only one path in the collider:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof(PolygonCollider2D))]
public class DrawPolygonCollider2D : MonoBehaviour
{
[SerializeField] private GameObject linePrefab;
LineRenderer lineRenderer;
PolygonCollider2D polygonCollider2D;
void Start()
{
lineRenderer = Instantiate(linePrefab).GetComponent<LineRenderer>();
lineRenderer.transform.SetParent(transform);
lineRenderer.transform.localPosition = Vector3.zero;
polygonCollider2D = GetComponent<PolygonCollider2D>();
}
void Update()
{
HiliteCollider();
}
void HiliteCollider()
{
var points = polygonCollider2D.GetPath(0); // dumb assumption for demo -- only one path
Vector3[] positions = new Vector3[points.Length];
for(int i = 0; i < points.Length; i++)
{
positions[i] = transform.TransformPoint(points[i]);
}
lineRenderer.positionCount = points.Length;
lineRenderer.SetPositions(positions);
}
}