• 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 ikelaiah · Nov 25, 2013 at 05:25 AM · arrays

What is the best way to clear an array of Components?

I created an array to store all cameras in the scene as

 var cameras : Camera[];
 
 function Start() {
      cameras = GameObject.FindObjectsOfType(Camera) as Camera[];
 }

I'd like to clear the content of cameras. One way I can think of is;

 function ClearCameras(cams : Camera[]) {
      for(var c : Camera in cams) {
           c = null;
      }
 }

Is there a shorter way of doing this? Just imagine, having arrays that contain cameras, car, etc, would require significant amount of repetition of code.


EDIT

See replies of @vexe and @fafase below. Take the important note below about passing target array (to be cleared) into an extension method, DO NOT use ref. I did not want to return a new array out of the extension method.

Comment
Add comment
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

2 Replies

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

Answer by vexe · Nov 25, 2013 at 05:29 AM

If you were using a list you could do list.Clear(); - If it's just a regular array, just null the whole thing: cameras = null; as long as you don't have other references to the array, it will get garbage collected. Or just new it up again: cameras = new Camera[SIZE]; - (In C++, if you do cameras = null; that will be a memory leak since there's no garbage collection, so you have to go over each element and free it)

Comment
Add comment · Show 3 · 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 fafase · Nov 25, 2013 at 05:51 AM 1
Share

$$anonymous$$ain question is if he wants to clear the array and destroy the objects or just clear the array but keep the object.

Your answer will just clear the array which is what the questions seems to ask. If the first case, then you need Destroy as well.

Only are you wrong on one point, clearing the array will not make the objects collected. This is true in windows applications (considering there is no other reference to any of those objects), not in Unity. The objects are still in the scene, probably referenced in a list the scene keeps track of, so clearing the array will only break the link between the array and the objects and the array pointer point nowhere..

avatar image vexe · Nov 25, 2013 at 05:58 AM 0
Share
  • Correct - He should clarify a bit more. If it was an array of ints, strings, floats and anything that's not instantiate-able in the scene it will get collected and array = null; is enough - but if it was an array of Objects (cameras, rigidbodies, gameObjects, etc) - he should worry about Destroying them as well.

avatar image ikelaiah · Nov 25, 2013 at 09:47 PM 0
Share

Ah! I was under impression that nulling (every)things would tell the GC to get rid of them (destroy). Certainly I was wrong. Thanks for the insight @vexe.

avatar image
2

Answer by fafase · Nov 25, 2013 at 06:03 AM

There is no shorter way to perform your action. You could though create an extension method so that it is done in one line:

 public static class Utility{
    public static Object[] ClearArray(this Object[] array){
        foreach(Object obj in array)
        {
            if(obj != null)
                Destroy(obj);
        }
        return null;
    }
 }

then use:

cameras = cameras.ClearArray();

Note: you have to do this little trick above of assigning into the array because you cannot use extension method with a reference of the object.

Comment
Add comment · Show 6 · 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 vexe · Nov 25, 2013 at 06:08 AM 1
Share

Hmm, Camera is not a GameObject - Camera is a Behaviour which is a Component which is a Object. Since both GameObject and Component ultimately inherits Object I think it makes sense to make the extension for UnityEngine.Object[] ins$$anonymous$$d of GameObject[]

avatar image vexe · Nov 25, 2013 at 06:16 AM 0
Share

"Note: you have to do this little trick above of assigning into the array because you cannot use extension method with a reference of the object." - Could you clarify what you meant with that line a little bit? - did you mean I can't do: myRef.myExt();?

avatar image fafase · Nov 25, 2013 at 06:21 AM 0
Share

Indeed the Camera is a component but you would just have to change the type, this was more generic example. I changed it to Object.

As for trick explanation you cannot do:

 public static GameObject[] ClearArray(ref this GameObject[] array);

What you are getting inside the methods is a copy of the reference to the array so modifying 'array' does not affect the actual array outside, just the copy of the pointer inside the method.

avatar image vexe · Nov 25, 2013 at 06:28 AM 1
Share

Right. @ikelaiah if that sounded confusing for you, take a look at this. An eye opener by Jon Skeet :)

avatar image Bunny83 · Nov 26, 2013 at 12:24 AM 3
Share

As generic method it would make more sense because you can't do

 cameras = cameras.ClearArray();

without a cast to the actual array type.

 public static class Utility
 {
     public static T[] ClearArray<T>(this T[] array) where T : Object
     {
         foreach(T obj in array)
         {
             if(obj != null)
                 Destroy(obj);
         }
         return (T[])null;
     }
 }

However i don't see the point in returning a constant value. That doesn't make much sense and the function name doesn't give a hint about this (strange) behaviour.

A name like DestroyAll would fit better. Also note that there could be other references to the same array which would keep the array alive anyways.

Something like that would be much more readable:

 DestroyAll(array);
 array = null;
Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

18 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How can I check values of all array/List quickly 1 Answer

Sequence Scripting 2 Answers

Convert BuiltIn array to an Generic List? 1 Answer

Pair Switch Cases to individual elements in a Vector3 array? 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