Question by
Miso21 · Nov 08, 2018 at 01:38 PM ·
instantiatearrayienumeratorfor-loopindexoutofrangeexception
I want to make make a plant to grow after few seconds.
So every time i click on field and when 2 seconds are dont i got this error:
IndexOutOfRangeException: Array index is out of range. fieldManager+c__Iterator0.MoveNext () (at Assets/Scripts/fieldManager.cs:47) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fieldManager : MonoBehaviour {
public GameObject [] fields;
public GameObject plantInstance;
public float timeToGrow;
private int i;
void Update()
{
fieldFinding();
}
public void fieldFinding()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit, 100))
{
if (hit.transform.gameObject.tag == "fields")
{
for (i = 0; i < fields.Length; i++)
{
if (hit.transform.name == fields[i].name)
{
//Instantiate(plantInstance,fields[i].transform.position, Quaternion.identity);
StartCoroutine(Plant(fields));
}
}
}
}
}
}
IEnumerator Plant(GameObject[] FieldsArray)
{
yield return new WaitForSeconds(timeToGrow);
Instantiate(plantInstance,FieldsArray[i].transform.position, Quaternion.identity);
}
}
Comment