Debug draw sphere script

Hi, i’ve searched for a way to replicate the Debug.DrawRay utility for other primitives like sphere, box ecc… and found none or at least they say you can use gizmo but still i preferred making my own script to be more flexible, it is callable from everywhere with no need to instantiate gameobject in the scene from the editor or add properties where you need to debug:

using System.Collections;
using UnityEngine;

public static class DebugUtilities
{
    /// <summary>
    /// Draw primitive forms like capsule, cubes ecc... for a N time in a location.
    /// (similar to Debug.DrawRay)
    /// </summary>
    public static void DrawPrimitive(Vector3 position, float scale, PrimitiveType primitiveType, Color color, float time = 1f)
    {
#if UNITY_EDITOR
        GameObject sphere = GameObject.CreatePrimitive(primitiveType);
        sphere.transform.localScale = new Vector3(scale, scale, scale);
        sphere.transform.position = position;
        sphere.GetComponent<Renderer>().material.color = color;
        sphere.AddComponent<DestroySelf>().time = time;
#endif
    }
}

public class DestroySelf : MonoBehaviour
{
    public float time = 1f;

    public void Start()
    {
        StartCoroutine(SelfDestruct());
    }

    private IEnumerator SelfDestruct()
    {
        yield return new WaitForSeconds(time);
        Destroy(gameObject);
    }
}


Example

here i’m just calculating the target position after a click on the map, to se where i’ll land i spawn a debug green sphere where the object will arrive.

(Ignore the green ray, it’s from the other rayCast)

        Ray ray = Camera.main.ScreenPointToRay(_touchMoveAction.ReadValue<Vector2>());
        
        if (Physics.Raycast(ray, out RaycastHit hit, 1000f))
        {
            Vector3 directionFromPlayerToHitpoint = hit.point - _player.transform.position;
            targetDirection = new Vector3(+
                directionFromPlayerToHitpoint.x,
                0,
                directionFromPlayerToHitpoint.z
            );
            targetPosition = _player.transform.position + targetDirection;

            //player to point direction - DEBUG
            Debug.DrawRay(_player.transform.position, directionFromPlayerToHitpoint, Color.red, 3);
            
            //player to targetDirection - DEBUG
            Debug.DrawRay(
                _player.transform.position,
                targetDirection,
                Color.green, 3);

            //future player position - DEBUG <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            DebugUtilities.DrawPrimitive(targetPosition, 1f, PrimitiveType.Sphere, Color.green, 3f);
        }
        else
        {
            Debug.Log("Miss");
        }

The only ugly thing is that it’s showed in game too, but it’s not a problem since i’ve used unity directives to avoid instantiating anything in a release build.

1 Like