- Home /
How do i access the variables of a class that is in an array?
I have a class called Data with 2 variables, Sprite and int. This class is placed inside of an array. How do i access the variables of the class for each element in the array? I looked for hours but i don't think i have found my answer, or its possible i did and didn't realize it because i'm pretty new to C# and Unity, so any help is appreciated.
Just a little insight as to what i'm trying to do, its a 3x3 slot machine and i want to have it choose a sprite but each sprite has a percent chance to be picked. I have not setup any code for checking percentages or anything because i have been stuck here for a few hours trying to figure this out lol. There is a large chance i am doing this totally wrong so sorry if it is.
public class IntUtil : MonoBehaviour {
public class Data
{
public Sprite sprite;
public int chance;
}
// slots array is just the image that will show the random sprite that is chosen.
public Image[] slots;
public Data[] dataArray;
public Button spinButton;
private float timer = 0f;
private void Start()
{
ChangeImage();
}
private void Update()
{
timer -= Time.deltaTime;
if (timer > 0f)
{
spinButton.enabled = false;
ChangeImage();
}else
{
spinButton.enabled = true;
}
}
private void ChangeImage()
{
foreach (Image randImage in slots)
{
// here is where i am trying to access the sprite variable that is inside the class that is part of the data array.
int num = Random.Range(0, dataArray.Length);
randImage.sprite = dataArray.sprite[num];
}
}
public void StartTimer()
{
timer = 1.5f;
}
void CheckPercentage()
{
}
}
Answer by luiscmendez · May 16, 2018 at 12:44 AM
Just to be clear, are you attempting to access the variables of the class for each item in the array, or one item in specific at any given time?
It would check all items and then choose 1 based on the percent chance of being picked if that makes sense.
Ah, ok. So aside from the percentages game and all that, you seem to basically be on the right track.
What you’re essentially doing up there is attempting to access the sprite array in dataArray by adding the [num] at the end. You might want something more like this:
dataArray[num].sprite;
Same deal for the int value in dataArray[].
For the percentages thing you might store the percentage value in the dataArray and do a foreach or a for loop to decide which element to select in the dataArray[]