0

So I copied this script that randomly takes one value from the list and than writes it down on the console, and than I wanted to make so if some value got picked than the same that value would be deleted from the list. But I found the problem in which the value that got picked is not in intiger form. It is set as var and i don't know how to change it nor convert it. My goal is either to find a way to set that var to int or to somehow delete it from my list using var state. I am headbanging at this problem for hours now and can't solve it. Here is my code... Thanks in advance.

List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<T> GetRandomElements<T>(List<T> inputList, int count)
    {
        List<T> outputList = new List<T>();
        for (int i = 0; i < count; i++)
        {
            int index = Random.Range(0, inputList.Count);
            outputList.Add(inputList[index]);
        }
        return outputList;
    }

    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            var randomList = GetRandomElements(list, 1);

            Debug.Log("All elements =>  " + string.Join(", ", list));
            Debug.Log("Random elements => " + string.Join(", ", randomList));
            Debug.Log("*****************************");

            RemoveElement(ref list, randomList);
        }
    }

    private void RemoveElement<T>(ref T[] arr, int index)
    {
        for (int i = index; i < arr.Length - 1; i++)
        {
            arr[i] = arr[i + 1];
        }

        Array.Resize(ref arr, arr.Length - 1);
    }

1 Answers1

0

var is an implicitly typed variable. It takes on whatever data type is assigned to it at compile time. In this case

var randomList = GetRandomElements(list, 1);

Is a list of integers because GetRandomElements is accepting a list of integers as a parameter and returning a list of integers.

T-Rev
  • 92
  • 8
  • And how that helps? – Leon Ristic Aug 10 '22 at 17:44
  • You stated that your goal was to set that var to an int. I was telling you that the code already does this for you. it's an implicitly typed variable of type int since it's the result of a function returning a list of integers. – T-Rev Aug 10 '22 at 17:58