When I change the direction of the laser it causes a StackOverflow
. It only does it in certain directions as well, I know stack overflows are caused when code is being called to many times but can’t see the reason why it does it in my code and in certain directions.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LaserBeam
{
Vector3 pos, dir;
public GameObject laserObj;
LineRenderer laser;
List<Vector3> laserIndices = new List<Vector3>();
public LaserBeam ( Vector3 pos , Vector3 dir , Material material )
{
this.laser = new LineRenderer();
this.laserObj = new GameObject();
this.laserObj.name = "Laser Beam";
this.pos = pos;
this.dir = dir;
this.laser = this.laserObj.AddComponent(typeof(LineRenderer)) as LineRenderer;
this.laser.startWidth = 0.1f;
this.laser.endWidth = 0.1f;
this.laser.material = material;
this.laser.startColor = Color.green;
this.laser.endColor = Color.green;
CastRay(pos, dir, laser);
}
void CastRay ( Vector3 pos , Vector3 dir , LineRenderer laserbeam )
{
laserIndices.Add(pos);
//UpdateLaser();
Ray ray = new Ray(pos, dir);
RaycastHit hit;
if(Physics.Raycast( ray, out hit, 30))
{
CheckHit(hit,dir,laser);
}
else
{
laserIndices.Add(ray.GetPoint(30));
UpdateLaser();
}
}
void UpdateLaser ()
{
int count = 0;
laser.positionCount = laserIndices.Count;
foreach( Vector3 idx in laserIndices )
{
//Debug.Log("1");
laser.SetPosition(count, idx);
count++;
}
}
void CheckHit ( RaycastHit hitInfo , Vector3 direction , LineRenderer line )
{
if (hitInfo.collider.gameObject.tag == "Mirror")
{
Vector3 pos = hitInfo.point;
Vector3 dir = hitInfo.transform.forward;
CastRay(pos, dir, line);
}
else if (hitInfo.collider.gameObject.tag == "Endpos")
{
Debug.Log("You win");
laserIndices.Add(hitInfo.point);
UpdateLaser();
}
else if (hitInfo.collider.gameObject == laser)
{
laserIndices.Add(hitInfo.point);
UpdateLaser();
}
/*else
{
laserIndices.Add(hitInfo.point);
//UpdateLaser();
}*/
}
}