I am attempting to clear an array prior to rebuilding it and am getting a declaration error I don’t understand.
“Assets/Scripts/SetToppings.cs(42,27): error CS0844: A local variable pieces' cannot be used before it is declared. Consider renaming the local variable when it hides the member
SetToppings.pieces’”
here is my code. Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class SetToppings : MonoBehaviour {
public Text Item;
public Text price;
public string[] pieces = new string[0];
public string[] prices = new string[0];
public void RemoveTopping(){
Array.Clear (pieces, 0, pieces.Length);
Array.Clear (prices, 0, pieces.Length);
.
.
.
Ok first of all the error you quoted is about a piece of code you did not include in your question. However it seems you declared another local variable with the same name “pieces” inside a method. This results in a name collision.
Next thing is arrays have a fix size that can’t be changed. You created two empty string arrays. So they can’t hold a single element. Again arrays can’t be resized. You actually have to create a new array with a larger / smaller size and copy the old elements you want to keep over.
Next Array.Clear is just a helper method which iterates through all elements of your array and sets each element to the default value of the element type. The default value for string is null. This does not “remove” the elements.
If you need a dynamic collection of things you better use a generic List. A List internally uses an actual array to hold the elements but it tries to minimize the reallocation of the internal array. A List has an Add and Remove method. It allows the same random access as an array does.
public List<string> pieces = new List<string>();
Initially the List is empty. You can add elements by using:
pieces.Add("Some string");
You can also clear the whole list by using
pieces.Clear();
Now the list is empty again. You can check how many elements are in the List by using the Count property:
for(int i = 0; i < pieces.Count; i++)
{
Debug.Log("Element #"+i+" == " + pieces*);*
}
Wouldn’t it be easier if you use list instead .
public List<string> pieces = new List<string>
//here is adding the value
pieces.Add(SomeValue)
//here is the clearing of value
pieces.Clear();
I guess you’re currently declaring new variables and this has the effect of hiding the class members. The compiler also thinks you’re using those declared variables earlier in the function which is causing the error.
Hope it helps
That does clarify some things. I was re-declaring the array later in the method. I am going to try redoing the code as a list. I just need to figure out how to use the Split function with lists since it normally returns an array.
pieces = ToppingData.ToppingA1.Split ('/');
prices = ToppingData.PriceA1.Split ('/');
I’ll see what I can do and re-post any issues.