Array index is out of range??? (Day Night Cycle Script)
Hi unity community
I got this error and i dont know what it means: IndexOutOfRangeException: Array index is out of range. DayNightCycle.ChangeTime () (at Assets/Models + Scripts/Scripts/CSharp/DayNightCycle.cs:38) DayNightCycle.Update () (at Assets/Models + Scripts/Scripts/CSharp/DayNightCycle.cs:25)
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
public class DayNightCycle : MonoBehaviour
{
public float time;
public TimeSpan currenttime;
public Transform SunTransform;
public Light Sun;
public Text timetext;
public int days;
public float intensity;
public Color fogday = Color.grey;
public Color fognight = Color.black;
public int speed;
// Update is called once per frame
void Update ()
{
ChangeTime ();
}
public void ChangeTime()
{
time += Time.deltaTime * speed;
if (time > 86400)
{
days += 1;
time = 0;
}
currenttime = TimeSpan.FromSeconds (time);
string[] temptime = currenttime.ToString ().Split ("+"[0]);
timetext.text = temptime [0] + ":" + temptime [1];
SunTransform.rotation = Quaternion.Euler (new Vector3 ((time - 21600) / 86400 * 360, 0, 0));
if(time < 43200)
intensity = 1 - (43200 - time) / 43200;
else
intensity = 1 - ((43200 - time) / 43200 *-1);
RenderSettings.fogColor = Color.Lerp (fognight, fogday, intensity * intensity);
Sun.intensity = intensity;
}
}
can someone help me?
Answer by Caruzo · Apr 15, 2017 at 01:13 PM
Check out 35-39 lines. It has something to do with the array.
The error you get means that you are trying to access (use) or assign a new value to the string array number, which does not exist or has not been created yet.
I believe its this line: timetext.text = temptime [0] + ":" + temptime [1];
but i cant figure what i did wrong...
It would be nice to see if you actually add strings to the array. Simply put Debug.Log (temptime.length) under update to see if this number is ever changing to a higher one. If it stays the same it means you are not adding anything to array. Normally you add values to an array by 'array.add' or 'array.push'.