- Home /
How do I remove a specific item from a list?,How would I remove a specific item in a list?
I want to be able to remove the specific object that leaves the area, target.remove(target[i]) does not really solve my issue.
private void OnTriggerExit(Collider collision) { int numTargs = target.Count; for (int i = 0; i < numTargs; i++) { RaycastHit InRange; Ray enterRay = new Ray(transform.position, -(transform.position - target[i].transform.position)); Debug.DrawRay(transform.position, -(transform.position - target[i].transform.position)); if (Physics.Raycast(enterRay, out InRange, sightRange)) { if (InRange.collider) { target. } } }
},I tried using target.remove(target[i]), which sort of works the way I want it to, but it will always remove the first item from the list, I want the object that leaves the area to be removed from the list instead.
private void OnTriggerExit(Collider collision) { int numTargs = target.Count; for (int i = 0; i < numTargs; i++) { RaycastHit InRange; Ray enterRay = new Ray(transform.position, -(transform.position - target[i].transform.position)); Debug.DrawRay(transform.position, -(transform.position - target[i].transform.position)); if (Physics.Raycast(enterRay, out InRange, sightRange)) { if (InRange.collider) { target. }} } }
Answer by pauldarius98 · Feb 26, 2021 at 02:08 PM
If the targets leaving the area are triggering the OnTriggerExit event then you can do it without further raycasts using Linq with the following code:
private void OnTriggerExit(Collider collision)
{
var targetIndex = target.IndexOf(t => t == collision.gameObject);
if (targetIndex >= 0)
{
targets.RemoveAt(targetIndex);
}
}
just make sure that you declare using System.Linq;
Why do you use a loop when you use a linq expression inside the loop that is not even related to the loop? Also instead of using such a linq expression you could simply use RemoveAll.
GameObject obj = collision.gameObject;
target.RemoveAll(t=>t == obj);
This will remove all elements that match the given gameobject instance. So if it's in the list several times, all those instances will be removed.
Haha, silly me, i copied his code then did the change and forgot to remove the loop. I updated the code. And yes, your version works too and is shorter
Answer by nursedayuksel · Feb 26, 2021 at 01:30 PM
https://answers.unity.com/questions/589066/removing-from-a-list.html This might be helpful
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Item not being taked off from the List 1 Answer
Remove all duplicates from a list 1 Answer
Removing objects from a list in C# 2 Answers