- Home /
Is it posible to use a single function to change any property plugged in to it?
So I have a small "shop" that allows the player to increase or decrease their workforce. I am trying to use a combination of buttons to enable the player to do so, but I don't want to write multiple functions when one will suffice.
This is, essentially what I am trying to simplify:
public void AddToProperty1()
{
player.properties.Property1++;
}
public void AddToProperty2()
{
player.properties.Property2++;
}
// and so on...
Ideally, it would look something like...
public void AddToProperty(string property)
{
player.properties.property++;
}
But this code doesn't work, something is missing or this is not how I communicate to the computer what I am trying to do. Is it possible to simplify the function in this way?
Answer by Lilius · Feb 23, 2018 at 07:22 PM
You could add switch inside your method:
int property1;
int property2;
public void AddToProperty(string property)
{
switch (property)
{
case "property1":
property1++;
break;
case "property2":
property2++;
break;
}
}
Answer by homer_3 · Feb 23, 2018 at 08:10 PM
You could store your properties in an array and use an enum to ID each one, then pass an enum into the increment function like
enum PropertyEnum { PROP1, PROP2, PROP3};
List<int> properties;
public void AddToProperty(PropertyEnum propId)
{
properties[(int)propId]++;
}
Answer by TheAltbacker · Feb 23, 2018 at 08:58 PM
You could also overload 'AddToProperty' so whenever you call it, it does slightly different things based on parameters and return type. You could pass in a reference to your property, so you'd always be changing the one currently passed in.
public void AddToProperty(ref float _floatProperty)
{
_floatProperty++;
}
public void AddToProperty(ref int _intProperty)
{
_intProperty++;
}
//etc.
Haven't tested this, so it might not work exactly how I imagine, but I do think it's a viable idea.
Your answer
Follow this Question
Related Questions
C# - parsed strings not changing in function 1 Answer
String Arrays in a function 0 Answers
Using a string to call a function from another script without "SendMessage" 2 Answers
Making an in-game command line. How do I get arguments? 1 Answer
Get Object, Trigger Attached Method,Trigger method on collider script 1 Answer