Home > Back-end >  How to create a Gizmos which renders the bounds of a BoxCollider2D?
How to create a Gizmos which renders the bounds of a BoxCollider2D?

Time:12-18

I want to draw a Gizmos atop a BoxCollider2D, but the Gizmos does not show up in the Scene view; with no errors in the console.

My current code:

void OnDrawGizmos()
{
    Gizmos.color = Color.red;
    Gizmos.DrawWireCube(boxCollider.bounds.center, boxCollider.bounds.size);
}

The image of the enemy and no Gizmos.

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:

  1. The script containing the OnDrawGizmos() function isn't attached to the same GameObject with the BoxCollider2D component.

  2. 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: Gizmos Icon in the toolbar

  3. By default, Gizmos will not be drawn in the Game 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 the Scene view.

  4. Your boxCollider variable isn't assigned to the BoxCollider2D component of the GameObject, 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.

enter image description here

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);
    }
}
  • Related