- Home /
The question is answered, right answer was accepted
Getting StackOverflowException from raycasts on a prefab object
I have this setup for collision detection:
public class FishController : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D boxCollider;
public LayerMask collisionLayer;
public float moveSpeed;
public float raycastDistance;
private Vector2 direction;
private void Awake()
{
rb = gameObject.GetComponent<Rigidbody2D>();
boxCollider = gameObject.GetComponent<BoxCollider2D>();
ChooseTargetLocation();
}
private void FixedUpdate()
{
CheckForObstacle();
rb.MovePosition(rb.position + (direction.normalized * moveSpeed * Time.deltaTime));
}
private void ChooseTargetLocation()
{
direction = Random.insideUnitCircle;
RaycastHit2D hit = Physics2D.Raycast(rb.position, direction, raycastDistance, collisionLayer);
if (hit.collider != null)
{
ChooseTargetLocation();
}
}
private void CheckForObstacle()
{
RaycastHit2D hit = Physics2D.Raycast(rb.position, direction, raycastDistance, collisionLayer);
Debug.DrawRay(rb.position, direction.normalized * raycastDistance, Color.red);
if (hit.collider != null)
{
Debug.Log("hit");
ChooseTargetLocation();
}
}
}
This was working fine, up until I turned the gameObject holding FishController into a prefab. Suddenly, the moment I hit play, I get a StackOverflowException.
FishController.ChooseTargetLocation () (at Assets/Scripts/FishController.cs:31) FishController.ChooseTargetLocation () (at Assets/Scripts/FishController.cs:34) FishController.ChooseTargetLocation () (at Assets/Scripts/FishController.cs:34) ...
And line 34 runs forever. This even happens when I remove any object from the collisionLayer. There is nothing the ray could be hitting. Anyone know whats going on here?
Lol yep. I'm dumb, really should've been able to figure that one out. Thanks!
Follow this Question
Related Questions
Can't find the null reference 1 Answer
How to specify which version of a method to use 0 Answers
Instantiate a prefab and parenting it? 1 Answer
How to rotate a player around the corner of a box? 0 Answers
Destroying a prefab with a prefab? 2 Answers