0
\$\begingroup\$

As per https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays
I have initialized my jagged array as follows:

private float[][] bulletBehaviour;

void Start()
{
    float[][] bulletBehaviour = new float[1][]
    {
        new float[4] {12.0f, 0.3f, 0.5f, 0.5f} // [typeSelected][speed, size, lifeTime, fireRate, damage]
    };
}

Then any time I try to use bulletBehaviour elsewhere it gives the error in the title.
Note: There will be more arrays eventually (if I can get them working)

Thanks!

\$\endgroup\$
2
\$\begingroup\$

Inside your Start() method, delete the float[][] before assigning a value to the variable, like so:

private float[][] bulletBehaviour;

void Start()
{
     /* Before:
    float[][] bulletBehaviour = new float[1][]
    After: */
    bulletBehaviour = new float[1][]
    {
        new float[4] {12.0f, 0.3f, 0.5f, 0.5f} // [typeSelected][speed, size, lifeTime, fireRate, damage]
    };
}

Why?

When you start a line with a variable type, you're telling the compiler "I'm defining a new variable of this type."

So you were creating a new local variable called bulletBehaviour, and everything that followed assigned a value to this local variable, not the member variable that you defined in the body of the class itself. So the member variable stayed unassigned (null).

If for some reason you need to have a local variable or argument of the same name inside a method, you can still refer to the member variable by qualifying it with this. like so:

string greeting = "Hello";

public void MyMethod() {
    string greeting = "Yo";

    Debug.Log(greeting);  // Refers to the local variable - outputs "Yo"
    Debug.Log(this.greeting); // Refers to the member variable - outputs "Hello"
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Ah, thank you so much. I've been self-teaching, so the explanation really helps! \$\endgroup\$ – Devintage Sep 4 '18 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.