Assaigning objects in class
When I try to assigning "Attendance Items" in the class:
public class Attendance
{
public Camera eventCamera;
public GameObject eventTrigger;
public GameObject msgZeCanvas;
public obslObj [] AttendanceItems ;
}
whose elements are:
public class obslObj
{
public GameObject items;
public Rigidbody rbItem;
}
when I try iteration in loop I have problem, because I cannot relate to the length of the array's function.
Lenght:
for (int i=0; i<Attendance.AttendanceItems.Length; i++)
as well as
foreach (obslObj item in Attendance.AttendanceItems)
which are included in another class:
public class AttendanceEventScript: MonoBehaviour
When I try to compile I get the error:
AttendanceEventScript.cs (39,69): error CS0120: An object reference is required is access non-static member `Attendance.AttendanceItems'
Any ideas?
Answer by Dave-Carlile · Dec 18, 2015 at 07:23 PM
You're trying to work with the Class, but you must create an Instance of the class and work with that. The class is just a data type.
// create an instance of the Attendance class
Attendance attendance = new Attendance();
// now you can access properties...
attendance.eventCamera = myCamera;
Now, inside of your Attendance class you have an array of obslObj. That array reference is going to start out as null, so you have to create it and specify a length. If it's a constant size, the easiest way is when you declare the Attendance class...
public class Attendance
{
...
// allocate the array using new...
public obslObj [] AttendanceItems = new obslObj[10];
}
Now you can access the array...
Debug.Log("length=" + attendance.AttendanceItems.Length);
Your answer
Follow this Question
Related Questions
Having problems with custom objects in my array - BCE0019 0 Answers
NullReferenceException: Object reference not set to an instance of an object 0 Answers
Unity 3D C# - Making Classes Act Like An Array 3 Answers
[SOLVED] Increase and Decrease size of Class Array in Unity C# 1 Answer
How to get an object (that is a prefab) from an array and instantiate it (C#) 1 Answer