- Home /
IndexOutOfRange when using Lerp
So here is the relevant code:
void Update () {
//t += Time.deltaTime;
//print(t);
renderer.material.color = Color.Lerp(start, end, 5);
if (renderer.material.color.a <= 0.0)
Destroy(gameObject);
}
So I don't get why it's giving the IndexOutOfRange exception. I'm most certainly sure that it's the number I give it(5 in this case). I have even tried putting an f after the numner(like 5f) to make sure it's a float but to no avail. Any clarification would be really helpful. Maybe I'm just not understanding Lerp enough.
Edit: So I noticed that this isn't all the relevant code. The exception is actually happening in a whole different class which is this one:
public class RandomSprite : MonoBehaviour {
public Sprite[] sprites;
public string resourceName;
public int currentSprite = -1;
// Use this for initialization
void Start () {
if (resourceName != "") {
sprites = Resources.LoadAll<Sprite>(resourceName);
if (currentSprite == -1)
currentSprite = Random.Range(0, sprites.Length);
else if (currentSprite > sprites.Length)
currentSprite = sprites.Length - 1;
**GetComponent<SpriteRenderer>().sprite = sprites[currentSprite];**
}
}
The line within the asterisks .. is the line that the error is pointing to.
Answer by robertbu · Sep 28, 2014 at 10:06 PM
There is nothing here that will generate an IndexOutOfRange. You need to provide your entire script and a copy of the exact error message from the console. As for this code, Lerp() takes values between 0.0 and 1.0. A value of 0.5 will produce an output half way between 'start' and 'end'. A value of 5 will get rounded to 1 and will return 'end'. There is an eased form of Lerp that can be used this way:
renderer.material.color = Color.Lerp(renderer.material.color, end, Time.deltaTime * 5.0);
Thanks for the correction. I have edited the original post.
That line will generate an error if the sprites array does not have any entries. That is, both lines 12 and 14 will set 'currentSprite' to 0, which is not valid for an empty array. If you see the array has entries in the inspector, look for a second copy of the script attached somewhere in your hierarchy.
Aren't arrays zero based? Why would currentSprite not work if it is set to zero? It will just be pointing to the first element of the array right?
If the array does not have any elements at all, there would be no first element to access and would give the IndexOutOfRange error, check it like @robertbu has pointed out to see if this is the case.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164000im_/https://answers.unity.com/themes/thub/images/avi.jpg)