Problem with List.Addrange
I was trying to create a dynamic array, apparently Unity does not like how I decided to type it. I tried it in a different script and it worked, but when I moved all the code to another script, Unity will not compile it.
So where is the problem and how can I resolve it in a way that allows me to do what I want?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public class CSHARPCONTROLLER : MonoBehaviour {
public bool in_prompt = false;
public bool object_selected = false;
public List<string> object_names;
public List<GameObject> all_objects;
void Start () {
object_names = new List<string> ();
all_objects = new List<GameObject> ();
}
public void AddName (GameObject object_added, string name) {
all_objects.AddRange (object_added);
object_names.AddRange (name);
UnityEngine.Debug.Log (name);
}
}
The error it gives me is this, and highlights exactly the lines where I try to use "AddRange".
Assets/Standard Assets/Script/CSHARPCONTROLLER.cs(27,29): error CS1502: The best overloaded method match for `System.Collections.Generic.List<UnityEngine.GameObject>.AddRange(System.Collections.Generic.IEnumerable<UnityEngine.GameObject>)' has some invalid arguments
it also gives this error
Assets/Standard Assets/Script/CSHARPCONTROLLER.cs(27,29): error CS1503: Argument `#1' cannot convert `UnityEngine.GameObject' expression to type `System.Collections.Generic.IEnumerable<UnityEngine.GameObject>'
For some strange reason it IS working as intended now, but I did not change anything except I stopped using "AddRange". Before when I stopped using it, it would not dynamically change the size of the List, but now it does? In any case, I still want to know what happened.
AddRange has to add a collection of GameObjects but you only put in one.
Answer by BenWiller1989 · Apr 13, 2021 at 10:12 PM
Accidentally stumbled over this. But for those, who have similar problems with that....
You can not add a single GameObject to AddRange() Statement! The same issue with the string. If you like to just Add a single Variable, then use List.Add(), not List.AddRange(), because AddRange expects a Range, not a single variable !