Home > other >  Gizoms wont draw in my Unity 2D game. No errors
Gizoms wont draw in my Unity 2D game. No errors

Time:12-17

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.

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