- Home /
Change a variable with ToString()
Is there a way of doing this, I have a global variable that is on a global script called GlobalVars ..
globalVarsScript.carType1Petrol[carNumber] = petrol;
what I'd like to do is change the 1 in carType1Petrol
to 2, 3, ect .. by using myInt.ToString()
.. can this be done as it's a variable ? And when I try it says " is not a member of 'GlobalVars' "
You cannot do what you are trying to do. You will need to make an array of CarTypePetrol. Then you can index:
globalVarsScript.carTypePetrol[type][carNumber] = petrol;
I read somewhere Unityscript doesn't have the syntax required to explicitly define the type of a jagged array, I thought it would be this ..
public var carTypePetrol : int[][] = new int[10][10];
So how would I initialize the above ?
Answer by MicroEyes · Jul 09, 2013 at 01:30 PM
You could use reflection. For example if PropertyName is a public property on MyClass and you have an instance of this class you could:
MyClass myClassInstance = ...
double temp = (double)typeof(MyClass).GetProperty("PropertyName").GetValue(myClassInstance, null);
If it's a public field:
MyClass myClassInstance = ...
double temp = (double)typeof(MyClass).GetField("FieldName").GetValue(myClassInstance);
Of course you should be aware that reflection doesn't come free of cost. There could be a performance penalty compared to direct property/field access.
Answer by tw1st3d · Jul 09, 2013 at 06:24 PM
You could make an enum for your car types.
enum CarTypes
{
Petrol;
Type2;
Type3;
}
tw1st3d, I dont think I can use an enum as I would have to do something like ..
switch (CarType) {
case carChoices.One:
fuel = carType1Petrol;
break;
case carChoices.Two:
fuel = carType2Petrol;
break;
case carChoices.Three:
fuel = carType3Petrol;
break;
default:
Debug.LogError("Unrecognized Option");
break;
}
But then if I put ..
globalVarsScript.fuel[carNumber] = petrol;
I get the error "fuel is not a member of 'GlobalVars' "
namespace CarType
{
public class CarTypes
{
public int CarType = 0;
public String fuel;
enum FuelTypes
{
PETROL;
FUEL2;
FUEL3;
}
public void FindCarType()
{
switch(CarType)
{
case 1:
fuel = FuelTypes.PETROL;
case 2:
fuel = FuelTypes.FUEL2;
case 3:
fuel = FuelTypes.FUEL3;
}
}
}
}
Your answer
