c# - Unity: NullReferenceException -
nullreferenceexception: object reference not set instance of object tower.ongui () (at assets/tower.cs:100)
relevant line is:
if(main.gold >= towers.u[stage])
the variables in towers defined so, doing wrong?
using unityengine; using system.collections; using system.collections.generic; public class towers : monobehaviour { public static float[] d; public static float[] r; public static float[] s; public static float[] u; // use initialization void start () { d = new float[10]; d[0] = 1f; d[1] = 3f; d[2] = 5f; d[3] = 7f; d[4] = 9f; d[5] = 11f; d[6] = 13f; d[7] = 15f; d[8] = 18f; d[9] = 21f; d[10] = 23f; r = new float[10]; r[0] = 5f; r[1] = 9f; r[2] = 13f; r[3] = 17f; r[4] = 21f; r[5] = 25f; r[6] = 29f; r[7] = 33f; r[8] = 37f; r[9] = 41f; r[10] = 45f; s = new float[10]; s[0] = 3f; s[1] = 2.8f; s[2] = 2.6f; s[3] = 2.4f; s[4] = 2.2f; s[5] = 2f; s[6] = 1.8f; s[7] = 1.6f; s[8] = 1.4f; s[9] = 1.2f; s[10] = 1f; u = new float[10]; u[0] = 50f; u[1] = 100f; u[2] = 150f; u[3] = 200f; u[4] = 250f; u[5] = 300f; u[6] = 350f; u[7] = 400f; u[8] = 450f; u[9] = 500f; u[10] = 0f; } }
thanks!
it seems either main
null or didn't call towers.start()
before line causing problem.
when initialising static fields that, can better use static initialisation declare fields, calling private static method returns initialisation data.
doing means don't need separate start()
method must remember call.
for example:
public class towers: monobehaviour { public static float[] d = initd(); public static float[] r = initr(); public static float[] s = inits(); public static float[] u = initu(); private static float[] initd() { return new [] { 1f, 3f, 5f, 7f, 9f, 11f, 13f, 15f, 18f, 21f, 23f }; } private static float[] initr() { return new [] { 5f, 9f, 13f, 17f, 21f, 25f, 29f, 33f, 37f, 41f, 45f }; } private static float[] inits() { return new [] { 3.0f, 2.8f, 2.6f, 2.4f, 2.2f, 2.0f, 1.8f, 1.6f, 1.4f, 1.2f, 1.0f }; } private static float[] initu() { return new[] { 50f, 100f, 150f, 200f, 250f, 300f, 350f, 400f, 450f, 500f, 0f }; } }
Comments
Post a Comment