Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Created January 13, 2022 18:56
Show Gist options
  • Save kurtdekker/539c021eac02c5b1a164691c5bd99afc to your computer and use it in GitHub Desktop.
Save kurtdekker/539c021eac02c5b1a164691c5bd99afc to your computer and use it in GitHub Desktop.
Visualize rays in Unity using LineRenderers
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);
}
}
}
@kurtdekker
Copy link
Author

To use:

	Vector3 position = Vector3.zero;
	for (int i = 0; i < 10; i++)
	{
		RayViz.Create(position, position + Random.onUnitSphere * Random.Range( 0.5f, 5.0f));
	}
	Debug.Break();		// pause

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment