Ertai7
1
I try to initialize an array of classes.
Since it’s only a prototype I decided to hardcode it for simplicity. The code is neither good practice nor beautiful, but that’s not my point.
My two classes look like this:
public class MyEvent
{
public int eventType;
public string eventText;
}
public class EventList {
private MyEvent[] myEventList = new MyEvent[10] ;
public void InitializeMyEvents()
{
MyEvent myEvent = new MyEvent();
myEvent.eventType = 1 ;
myEvent.eventText = "Alpha";
myEventList[0] = myEvent;
myEvent.eventType = 2 ;
myEvent.eventText = "Bravo";
myEventList[1] = myEvent;
Debug.Log(myEventList[0].eventText + ", " + myEventList[1].eventText);
}
}
When calling the InitializeMyEvents function I expected the output to be: Alpha, Bravo
Instead it is Bravo, Bravo.
Can anyone explain me why?
This is driving me mad.
Thanks!
Classes are referred to by reference. So you create a new ‘MyEvent’ on line 13 and get a reference back to that event. The rest of your code will be assigning to that one reference. So when you make changes on line 20 and 21, you are making changes to the only ‘MyEvent’ created. Both of your two index entries will refer to that one created instance of ‘MyEvent’. To solve this problem, add this on line 19:
myEvent = new MyEvent();
Note another solution to this problem would be to delcare ‘MyEvent’ as a structure. Then it would be referenced by value and not have the issue you have here.