Hi,
I have this script to get an object with a lowest variable value. However if I run it I get an error IndexOutOfRangeException on the first line(12) of the Add function. Any ideas?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BinaryHeap : MonoBehaviour
{
public GameObject[] binaryHeap;
private int numberOfItems;
public void Add(GameObject fCost)
{
this.binaryHeap[this.numberOfItems] = fCost;
int bubbleIndex = this.numberOfItems;
while (bubbleIndex != 1)
{
int parentIndex = bubbleIndex / 2;
if (this.binaryHeap[bubbleIndex].GetComponent<Node>().f_totalCost <= this.binaryHeap[parentIndex].GetComponent<Node>().f_totalCost)
{
GameObject tmpValue = this.binaryHeap[parentIndex];
this.binaryHeap[parentIndex] = this.binaryHeap[bubbleIndex];
this.binaryHeap[bubbleIndex] = tmpValue;
bubbleIndex = parentIndex;
}
else
{
break;
}
}
this.numberOfItems++;
}
public GameObject Remove()
{
this.numberOfItems--;
GameObject returnItem = this.binaryHeap[1];
this.binaryHeap[1] = this.binaryHeap[this.numberOfItems];
int swapItem = 1, parent = 1;
do {
parent = swapItem;
if ((2 * parent + 1) <= this.numberOfItems)
{
if (this.binaryHeap[parent].GetComponent<Node>().f_totalCost >= this.binaryHeap[2 * parent].GetComponent<Node>().f_totalCost)
{
swapItem = 2 * parent;
}
if (this.binaryHeap[swapItem].GetComponent<Node>().f_totalCost >= this.binaryHeap[2 * parent + 1].GetComponent<Node>().f_totalCost)
{
swapItem = 2 * parent + 1;
}
}
else if ((2 * parent) <= this.numberOfItems)
{
if (this.binaryHeap[parent].GetComponent<Node>().f_totalCost >= this.binaryHeap[2 * parent].GetComponent<Node>().f_totalCost)
{
swapItem = 2 * parent;
}
}
if (parent != swapItem)
{
GameObject tmpIndex = this.binaryHeap[parent];
this.binaryHeap[parent] = this.binaryHeap[swapItem];
this.binaryHeap[swapItem] = tmpIndex;
}
}
while (parent != swapItem);
return returnItem;
}
}