- Home /
Creating a class wide array (c#)
Hi everyone,
I have to create an array that i can use in in several functions, but if i want to create it I get an error
public class PosChanged : MonoBehaviour {
private int changeCount = 0;
private int breakForce = 20;
Vector3[] v = new Vector3[transform.childCount];
Vector3[] v_old = new Vector3[transform.childCount];
.....
I know I would have to do it in Start() because of the transform.childCount, but I cant access it then in FixedUpdate() if its created in Start().
So how do I do that?
Errormsg:
(8,35): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `UnityEngine.Component.transform'
Answer by Kryptos · May 02, 2012 at 11:15 AM
You have to declare the arrays as class members, but you initialize them in Start:
public class PosChanged : MonoBehaviour {
private int changeCount = 0;
private int breakForce = 20;
Vector3[] v;
Vector3[] v_old;
void Start()
{
v = new Vector3[transform.childCount];
v_old = new Vector3[transform.childCount];
}
Then you can access them inside other methods such as FixedUpdate:
void FixedUpdate()
{
v[0] //...
}
Exactly, the problem is that transform.childCount
is a property which executes a function on the transform component, but the field initializers are executed even before the constructor. so you have no access to other stuff there and you couldn't execute class functions there, only static stuff because static variables are initialized first. transform
is a non static property.
Even global int a=8; int[] B = new int[a];
will error out, complaining about non-static a
.