Hi guys, I bumped into a problem and I am stucked!
I have the following code. I made it simple but in real I have much more variables and I would have a lot of IF statements.
Is it possible to iterate through the class Resources? What I want is to count how many values have a value. I need to count them.
using System;
using UnityEngine;
public class MyClass : MonoBehaviour
{
[Serializable]
private class RewardClass
{
public Resources resources;
}
[Serializable]
private class Resources
{
public int coins;
public int titanium;
public int pc;
public int parts;
}
// Values are assigned in the inspector only.
[SerializeField] private RewardClass[] rewardClass;
private void Start()
{
int numberOfRewards = 0;
// I want to replace this with a foreach loop.
if (rewardClass[0].resources.coins > 0)
numberOfRewards++;
if (rewardClass[0].resources.titanium > 0)
numberOfRewards++;
if (rewardClass[0].resources.pc > 0)
numberOfRewards++;
if (rewardClass[0].resources.parts > 0)
numberOfRewards++;
// Something like this but it is not working, I am getting error.
foreach (var property in rewardClass[0].resources.Length)
{
if (property > 0)
numberOfRewards++;
}
}
}
int numberOfRewards = 0;
foreach (RewardClass reward in rewardClass)
{
if (reward.resources.coins > 0)
numberOfRewards++;
if (reward.resources.titanium > 0)
numberOfRewards++;
if (reward.resources.pc > 0)
numberOfRewards++;
if (reward.resources.parts > 0)
numberOfRewards++;
}
I would heavily recommend you to read up on C# fundamentals
Edit :
Ok i think i get your issue , one way you could do this is by using reflection , it enables you to do many things regarding the types , like inspecting them and iterating over their members.
Here , i used it to get the fields of the class “Resources” and then loops over the fields to get their value. NOTE : reflection is extremely expensive and not to be used every frame , should preferable be kept for heavy initialization stuff at the start of the game (or things of that nature)
it would look like this
using System;
using System.Reflection;
public class MyClass : MonoBehaviour
{
[Serializable]
private class RewardClass
{
public Resources resources;
}
[Serializable]
private class Resources
{
public int coins;
public int titanium;
public int pc;
public int parts;
}
// Values are assigned in the inspector only.
[SerializeField] private RewardClass[] rewardClass;
private void Start()
{
// get a list of all the field from the type "Resources"
FieldInfo[] fields = typeof(Resources).GetFields(BindingFlags.Public | BindingFlags.Instance);
int numberOfRewards = 0;
foreach (RewardClass reward in rewardClass)
{
// iterate over the fields
foreach(FieldInfo field in fields)
{
// use the fieldInfo to get the field's value from the current "reward" in the loop
int value = (int) field.GetValue(reward.resources);
// do the needed counting
if(value > 0)
{
numberOfRewards++;
}
}
}
}
}