Created
January 13, 2022 18:56
-
-
Save kurtdekker/539c021eac02c5b1a164691c5bd99afc to your computer and use it in GitHub Desktop.
Visualize rays in Unity using LineRenderers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
// @kurtdekker | |
// | |
// Simple way to throw visible rays into a scene using LineRenderers | |
// | |
// Useful for debugging raycasts. | |
// | |
// May be helpful to call Debug.Break() simultaneously | |
// so that you can investigate the scene and see what happened. | |
public class RayViz : MonoBehaviour | |
{ | |
const float DefaultLineWidth = 0.25f; | |
const float DefaultLifeTime = 2.00f; | |
const float DefaultRayLength = 2.00f; | |
float lifeTime; | |
// For when you have two endpoints in space | |
public static RayViz Create( | |
Vector3 startPoint, | |
Vector3 endPoint, | |
float lineWidth = DefaultLineWidth, | |
float lifeTime = DefaultLifeTime) | |
{ | |
var rayviz = new GameObject("RayViz.Create()").AddComponent<RayViz>(); | |
rayviz.lifeTime = lifeTime; | |
var LR = rayviz.gameObject.AddComponent<LineRenderer>(); | |
LR.useWorldSpace = true; | |
LR.startWidth = lineWidth; | |
LR.endWidth = lineWidth; | |
LR.SetPositions(new Vector3[] { | |
startPoint, | |
endPoint, | |
}); | |
// TODO: you might want to mark this DontDestroyOnLoad() if you | |
// need it to survive full scene loads. | |
return rayviz; | |
} | |
// For when you have a ray (and optionally a length) | |
public static RayViz Create( | |
Ray ray, | |
float rayLength = DefaultRayLength, | |
float lineWidth = DefaultLineWidth, | |
float lifeTime = DefaultLifeTime) | |
{ | |
return Create( | |
startPoint: ray.origin, | |
endPoint: ray.GetPoint(rayLength), | |
lineWidth: lineWidth, | |
lifeTime: lifeTime); | |
} | |
IEnumerator Start() | |
{ | |
if (lifeTime > 0) | |
{ | |
yield return new WaitForSeconds(lifeTime); | |
Destroy(gameObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use: