- Home /
C# Physics.LineCast Argument is Out Range
I'm trying to get a set of gameobject to connect to each with a Physics.LineCast. But I keep getting an error saying my argument is out of range. I think this is because i+1 doesn't exist but I need that argument to make one gameobject link to another. Is there a way to work around this and make i+1 exist?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LaserZigZag : MonoBehaviour {
public List<GameObject> gos = new List<GameObject>();
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
for (int i = 0; i < gos.Count; i++)
if (Physics.Linecast(gos[i].transform.position, gos[i+1].transform.position)){
Debug.DrawLine(gos[i].transform.position, gos[i+1].transform.position, Color.red);
}
}
}
Answer by HarshadK · Dec 15, 2014 at 05:37 AM
Yes you can. Just use:
for (int i = 0; i < gos.Count - 1; i++)
if (Physics.Linecast(gos[i].transform.position, gos[i+1].transform.position)){
Debug.DrawLine(gos[i].transform.position, gos[i+1].transform.position, Color.red);
}
}
The second argument to the for loop will be the one game object less than all the game objects present in the list and your second last game object will be connected to your last game object. Here your last game object is the i+1.
Your answer
Follow this Question
Related Questions
Trouble Understanding Vector3.Angle() Result 2 Answers
RigidBody Script Conflict 1 Answer
C# Check Physics.Raycast Once 0 Answers
C# Construct Line Links Over Time 0 Answers
Unexpected "Jumping" Behavior 0 Answers