using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;
[ExecuteAlways]
public class SliderManager : MonoBehaviour
{
public Slider slider;
public List<GameObject> Objects = new List<GameObject>();
public GameObject Model;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
SetSlider((int)slider.value);
}
protected void SetSlider(int x)
{
for (int i = 0; i < slider.value; i++)
{
bool mustBeAnObject = i < x;
if ((mustBeAnObject) && (Objects[i] == null))
Objects[i] = Instantiate(Model);
else if ((!mustBeAnObject) && (Objects[i] != null))
{
if (!Application.isPlaying)
{
Objects.RemoveAt(i);
DestroyImmediate(Objects[i]);
}
else
{
Objects.RemoveAt(i);
Destroy(Objects[i]);
}
}
}
}
}
when i used array before i did :
public GameObject[] Objects = new GameObject[100];
but now Objects is a type List so instead looping over the size of the Objects like when it was array i’m trying to loop over the Slider value so in this case the Slider value in the editor is 12 but i’m getting out of bound index at the line :
if ((mustBeAnObject) && (Objects[i] == null))
what i’m trying to archive is using the Slider to to create new objects when sliding to the right and when sliding the slider to the left to destroy the objects.
it was working fine when i used array of Objects but then i wanted to remove also the objects from the array it self when destroying because in the inspector after destroying the objects there were empty and missing fields left in the array.
so i wanted to remove the objects from the array in the Destroy part :
if (!Application.isPlaying)
{
Objects.RemoveAt(i);
DestroyImmediate(Objects[i]);
}
else
{
Objects.RemoveAt(i);
Destroy(Objects[i]);
}
but removing from array is not possible or hard so instead i want to use List but now getting this out of bound index error :
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <75633565436c42f0a6426b33f0132ade>:0)
SliderManager.SetSlider (System.Int32 x) (at Assets/SliderManager.cs:32)
SliderManager.Update () (at Assets/SliderManager.cs:23)
line 23 is inside the Update :
SetSlider((int)slider.value);
and line 32 is :
if ((mustBeAnObject) && (Objects[i] == null))