I need to get a random class, store in to a "global class" variable (so i can access it in other methods), but i cannot find any good way to do it, what i've been trying to do is work with object variables... I'm coming from python to c#, so the properties of object variables looks kind of a mystery to me... I have been searching how to make it work, but i could not find a proper way to do it without a bunch of if statements...
//There might not be all the necessary namespaces to run this code
using UnityEngine; //where the random.range() came from
public class man1 //Initialization of the first class
{
public int val = 1;
}
public class man2 //Initialization of the second class
{
public int val = 2;
}
public class man3 //Initialization of the third class
{
public int val = 3;
}
public class allMan
{ //Where all classes 'merge'
private object chosenMan; //Where the chosen it's going to be stored
public allMan() //Constructor
{
//Have all man in one array to easily get the chosen from index
object[] men = new object[] { new man1(), new man2(), new man3() };
var choice = Random.range(0, men.Length); //Randomly get the index
chosenMan = men[choice]; // Atribute the chosen class
}
public void doActionWithChoosedMan()
{
Console.WriteLine(chosenMan.val); //ERROR
}
}
How should i approach this problem? Thanks.
One variable is typed as object by the compiler and all instance members will be verified as valid by the compiler. The other variable is typed as dynamic and all instance members will be ignored by the compiler and called by the DLR at execution time.
You can use dynamic
instead of object
public class allMan
{
//Where all classes 'merge'
private dynamic chosenMan; //Where the chosen it's going to be stored
public allMan() //Constructor
{
//Have all man in one array to easily get the chosen from index
object[] men = new object[] { new man1(), new man2(), new man3() };
var choice = Random.range(0, men.Length); //Randomly get the index
chosenMan = men[choice]; // Atribute the chosen class
}
public void doActionWithChoosedMan()
{
Console.WriteLine(chosenMan.val); //ERROR
}
}