Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by b1gry4n · Nov 06, 2014 at 08:38 AM · c#list

List Management. Removing from list and making sure item is not null

This is the way I have been removing objects from a list and making sure that they are not null:

     public void RemoveFromList(Transform targ){
         List<Transform> tempList = targetList;
         for(int i = 0; i < targetList.Count; i++) {
             if(targ == targetList[i]){
                 tempList.Remove(tempList[i]);
                 break;
             }
         }
         targetList = new List<Transform>();
         for(int i = 0; i < tempList.Count; i++) {
             if(tempList[i] != null){
                 targetList.Add(tempList[i]);
             }
         }
     }

My question is: Is this alright to do? How taxing is it to recreate lists on the fly like this? These lists do not contain many objects(yet) and I havent noticed any performance issues. I would like to plan for adding more objects to these lists and multiple calls to this function from different objects, but I am unsure if this is the correct method to do this or if there is a better way.

Thanks

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Vetpetmon · Nov 30, 2014 at 04:46 PM 0
Share

How do you know my code's name?!

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by GameVortex · Nov 06, 2014 at 09:06 AM

Seems to me like you can simplify that entire thing to: targetList.Remove(targ);

The Remove function of list removes the first occurrence of the object it finds and re-sizes the list.

You will most likely not see any immediate performance improvements until you have a lot of items in the list though.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image b1gry4n · Nov 06, 2014 at 09:16 AM 0
Share

I am either crazy or doing something wrong. I had it set to: targetList.Remove(targ); before but I was getting "null" objects in my lists. I wrote the above code to make sure I wouldnt receive null objects

EDIT: I remember why I wrote this. At one point I was trying to remove multiple objects from a list. When I iterated through the targetlist and called Remove(targ) it would throw the forloop off. You are right, removing a single object from a list using targetList.Remove(targ) should work.

An example of removing a list of objects from a list:

     public void RemoveList(List<Transform> targ){
         List<Transform> tempList = targetList;
         
         for(int i = 0; i < targetList.Count; i++) {
             for(int j = 0; j < targ.Count; j++) {
                 if(targ[j] == targetList[i]){
                     tempList.Remove(tempList[i]);
                     break;
                 }
             }
         }
         targetList = new List<Transform>();
         //I am pretty sure I could just do this...
 //        targetList = tempList;
         //but I want to be 100% that an item isnt NULL...
         for(int i = 0; i < tempList.Count; i++) {
             if(tempList[i] != null){
                 targetList.Add(tempList[i]);
             }
         }
     }

new code for single object removal:

     public void RemoveFromList(Transform targ){
 // I want to make sure the target actually exists in the list
         for(int i = 0; i < targetList.Count; i++) {
             if(targetList[i] == targ){
                 targetList.Remove(targ);
                 return;
             }
         }
     }
 


avatar image Linus · Nov 06, 2014 at 09:37 AM 0
Share

When removing one, you only need:

 targetList.Remove(targ);

If you for some reason need to know if anything was removed:

 public void RemoveFromList(Transform targ){
 bool isRemoved = targetList.Remove(targ);
 if(isRemoved == true){
 Debug.Log("Removed");
 } else {
  Debug.Log("Nothing to remove");
 }
 }
 


If you remove form the same list that you are looping, you will get errors.

Here is how I solved that problem (tips for improvment is welcome):

 public void CancelPickupTasks( PickUpAble PUA)
 {
     List<WorkTask> markedForRemoval = new List<WorkTask>();
     foreach (WorkTask task in WorkTask$$anonymous$$anager.instance.allWorkTasks)
     {

         if (task.type == WorkTaskType.PickupItem)
         {
   
              PickupTask pickupTask = task as PickupTask;
             if (pickupTask.objectToPickup.GetComponent<PickUpAble>() == PUA) {
  
                 
                 markedForRemoval.Add(task);
             }
  
         }
     }
     foreach (WorkTask task in markedForRemoval)
     {
         task.CancelTask(); //Basicly just WorkTask$$anonymous$$anager.instance.allWorkTasks.Remove() But I might want to do stuff if a task is cancelled
        
     }
 }

avatar image GameVortex · Nov 06, 2014 at 09:44 AM 0
Share

An easy way to remove from list while iterating through is to move the iterator back by one each time you are removing an object. This makes sure the iterator still matches the list and indices.

Example:

 for(int i = 0; i < list.Count; i++)
 {
     if(list[i] == target)
     {
          list.RemoveAt(i);
          i--;
     }
 }
avatar image Linus · Nov 06, 2014 at 09:48 AM 1
Share

Funny I went to the $$anonymous$$S docs and found a link at the buttom the page http://kristofverbiest.blogspot.no/2008/10/removing-items-from-collection.html Reversing seems like a good solution. Here is the $$anonymous$$S documentation for .Remove as well http://msdn.microsoft.com/en-us/library/cd666k3e%28VS.80%29.aspx

avatar image b1gry4n · Nov 06, 2014 at 09:49 AM 0
Share

@GameVortex - I just learned something new, haha. Thanks

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

28 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

Why does this return a NullReferenceException? 0 Answers

Passing lists to serialize and deserialize methods for XML parsing 0 Answers

CS0103 The name 'List' does not exist in the current context 1 Answer

Help Unity Script to C#!! 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges