I have tried many hours here my code snippet when i run the code it only remove the index I want to remove the name and print the name removed
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public List<string> names = new List<string>();
void Start()
{
foreach (var name in names)
{
Debug.Log(name);
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int index = Random.Range(0, names.Count - 1);
names.Remove(names[index]);
Debug.Log("Removed: " names[index]);
}
}
}
CodePudding user response:
If you have a random index with you, then first save the name to a variable, then use the same index to remove the item from the list
//Example names = { "suleiman", "Jon Skeet", "Prasad T"} & index = 2;
var nameTobeRemove = names[index]; //"Prasad T"
names.RemoveAt(index); // "Prasad T" removed
Console.WriteLine($"Removed name : {nameTobeRemove}"); //"Removed name :Prasad T"
Console.WriteLine($"New List : {string.Join(", ", names)}"); // New List : suleiman, Jon Skeet
The problem in your code is, you are not saving name
before removal, my above solution does that. It saves name
which is going to remove to a variable.