- Home /
Clear Entire Array, Set To Null(C#)
I Need Some Help With Clearing An Array Of GameObjects, Not Destroying The Objects, Just Removing Them From The Array. Another Way To Put This Is Set The Array To Null. I Have Looked At The Unity Scripting Reference, And It Says (NameOfArray).Clear(); Should Work, But I Tried RandDoor.Clear(); , And I Get The Compiler Error
Assets/Scripts(Mine)/Game/Moving Around The Castle/EnterCastleDoor.cs(34,26): error CS1501: No overload for method
Clear' takes 0' arguments
Help Anyone? Thanks!
-Seth
Answer by LividRabbit · Oct 15, 2013 at 09:52 PM
Array.clear has 3 parameters, Array array, int index , int length, if you want to clear the entire array, try Array.Clear(RandDoor, 0, RandDoor.Length);
Gives $$anonymous$$e Yet Another Error,
Assets/Scripts($$anonymous$$ine)/Game/$$anonymous$$oving Around The Castle/EnterCastleDoor.cs(35,17): error CS0103: The name `Array' does not exist in the current context
i have the same problem, and tried your method with my array name: Array.Clear(RandomImages, 0, RandomImages.Length); now "using System.Collections;" is at the 2nd line of my script, but still the error "Assets/Scripts/GameController.cs(79,13): error CS0103: The name `Array' does not exist in the current context" is displayed. what do?
The Array class is in the System namespace. The correct using directive is "using System;". Alternatively, you can just type "System.Array.Clear(RandDoor, 0, RandDoor.Length);"
Answer by vfxjex · Jul 01, 2015 at 04:54 AM
Why not just type
int[] a = new int[]{1,2,3,4};
//to clear
a = new int[4];
a will now equals to null; you don't even need to use System;
Haha! this is the best! I think we made a classic example of overcomplicating a rather simple issue
Well, if you still need the array this is actually not the best solution. It creates a new array and the old one will eventually get garbage collected. Using Array.Clear just sets the elements to null / default values. So using Array.Clear no new memory is allocated.
Btw: @Hoeloe already suggested this solution in a comment above about two years earlier.
Your answer
Follow this Question
Related Questions
correct method for clearing a gameObject array 4 Answers
Problem when trying to save variable in another variable. 1 Answer
help with memory leak 1 Answer
How to Make 2 dimension array of classes 1 Answer
Array index is out of range 1 Answer