- Home /
Array of classes wont set a length c#
hey so ime making a script that loops through a bunch of items a bunch of times and each item neads the some data stored so i set an array of clases but it seeams like i carnt set its length as when i accesses it it dosent apear to have any value and returns null anyway heres the array and class
public class Water{ public Vector2 curent = new Vector2 (0,0); public float CapedDirt = 0f; } public void Erode (){ Water[] Drops; float BlockErosionAmount = 0.05f; float maxCaped = 0.5f; Drops = new Water[1000]; for (int i = 0; i < MapSize*5; i++){ for (int w = 0; w < 1000; w++){ Vector2 start = new Vector2 (Random.Range(MapSize*0.25f,MapSize*0.75f),Random.Range(MapSize*0.25f,MapSize*0.75f)); print (Drops); print (Drops[w].curent); Drops[w].curent = start;// error coming from here
and hears the error its throwing at me
NullReferenceException: Object reference not set to an instance of an object MapGenBrush.Erode () (at Assets/Standard Assets/MapGenBrush.cs:98) MapGenBrush.CreateHeightMap () (at Assets/Standard Assets/MapGenBrush.cs:81) MapGenBrush.Start () (at Assets/Standard Assets/MapGenBrush.cs:25)
thanks for any help ime asuming this is just my inexperience with c# as ime used to js
Answer by Ashish Dwivedi · Feb 13, 2014 at 04:28 PM
Here you are initializing the array but not making the object that's why you are getting error. For creating 100 objects of "Water" class you need to write the following code:
Drops = new Water[1000];
for (int i = 0; i < Drops.Length ; i++)
{
Drops[i] = new Water();
}
You can understand better by this Reference. I hope now you would be able to understand.
k thanks i get it also am i right in thinking you mean drops.length
Yes, that was a printing mistake. I corrected that.Please remember to accept the answer if it is right for you.
Your answer
Follow this Question
Related Questions
how to construct all arrays (classes) with default constructor (not possible) 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Class and Array 1 Answer