I want to draw a gizmos ontop of a BoxCollider2D but it isn't showing up. I have no errors but no gizmos too. My current code:
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(boxCollider.bounds.center, boxCollider.bounds.size);
}
The Gizmos is not showing up and I have no idea why. No errors, no anything.
CodePudding user response:
Without knowing your exact scene set-up or what the rest of the code is like, it's difficult to tell. But there are several reasons why your Gizmos may not be displaying:
The script containing the
OnDrawGizmos()
function isn't attached to the sameGameObject
with theBoxCollider2D
component.The Gizmos option isn't
enabled
in the scene view. You can enable it by going to the top right corner of the scene view and clicking the small icon:By default,
Gizmos
will not be drawn in theGame
view, so if you're attempting to render them in this view, you'll need to enable them via the dropdown in a similar location as theScene
view.Your
boxCollider
variable isn't assigned to theBoxCollider2D
component of theGameObject
, although this would throw errors in the console.
The following snippet of code should reflect what you're trying to create:
[RequireComponent(typeof(BoxCollider2D))]
public class GizmosDemo : MonoBehaviour
{
// By using the RequireComponent attribute, we'll ensure a BoxCollider2D component exists
private BoxCollider2D _boxCollider;
private void Awake()
{
_boxCollider = GetComponent<BoxCollider2D>();
}
private void OnDrawGizmos()
{
// If we're not adding an Application.isPlaying check, the _boxCollider reference will be unassigned until Awake()
// So either if(!Application.isPlaying) return; or get the component as we do in the following code
var boxCollider = _boxCollider ? _boxCollider : GetComponent<BoxCollider2D>();
var bounds = boxCollider.bounds;
Gizmos.color = Color.red;
Gizmos.DrawWireCube(bounds.center, bounds.size);
}
}
CodePudding user response:
When there is an overlap, Collider
seems to have priority. 90% size makes the Gizmos.DrawWireCube()
appear.
test code:
using UnityEngine;
public sealed class GizmosTest : MonoBehaviour
{
[SerializeField] BoxCollider2D boxCollider;
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(boxCollider.bounds.center, boxCollider.bounds.size * 0.9f);
}
}