- Home /
C# array initialization
Hi to all.
I have a quick problem which I need to be solved.
Lately been looking into lots of C# tutorials, which helped a lot, but still there are some exceptions when using C# into Unity and regular using.
I initialize an array, which is called results, and set 5 elements to it. Now, what I want to do is initialize them in the script, and one more thing - if that is possible, they can hold a value of any int variable right?
Here's the code
using UnityEngine;
using System.Collections;
public class Label : MonoBehaviour {
int lives = 5;
public int[] results = new int[] {15, 1645, 135, 567};
// Use this for initialization
void Start () {
Debug.Log(results[1]);
}
// Update is called once per frame
void Update () {
}
}
It works fine if I initialize the values inside the editor, but this time it's not what I'm looking for. Thanks.
Answer by jahroy · Nov 26, 2011 at 02:37 AM
If you declare a variable as public, it can be edited in the Inspector.
Once the script has been attached to a GameObject, the init values in the script are ignored.
If those values were used, there would be no point of having the Inspector access.
Good point. If you want to init this only in the script, drop the public off of it.
Answer by ptdnet · Nov 26, 2011 at 02:21 AM
public int[] results;
void Update() {
results = new int[5];
results[0] = 324;
// etc...
}
Is that what you meant?
This is another way to do it, yes, but my mistake was with public. Thanks anyway!
Hi Everyone!
I have "y" number of arrays and each array with "x" number of elements.
How can i create such array in runtime ?
can anyone suggest ?
"y" and "x" are the values co$$anonymous$$g from server. (i want to store Textures in arrays)
Answer by Projectxx858xxGames · Oct 25, 2016 at 08:17 PM
@VamshiKrishnaP You need to use Vector2[]
The question is 5 years old and has already an accepted answer which addresses the actual problem correctly. So you bumped the question for no reason.
Apart from that your answer is just wrong in this case. He uses an int array. There's no point in using a Vector2 array.