I am trying to refactor some code and have to admit that I am new to the concept of generics.
I have a base class:
BaseVarDef.cs:
using UnityEngine;
public abstract class BaseVarDef<T> : ScriptableObject
{
[Multiline]
public string DeveloperDescription = "";
public T Value;
public void SetValue(T value)
{
Value = value;
}
}
Then I have several classes that derive from this. But they all contain the same 3 methods that I would like to refactor into this generic base class. The only difference is they expect either the generic type or class that is currently defining them.
FloatVar.cs
using UnityEngine;
[CreateAssetMenu(fileName = "New FloatVar", menuName = "Variables/FloatVar")]
public class FloatVar : BaseVarDef<float>
{
public void SetValue(FloatVar value)
{
Value = value.Value;
}
public void ApplyChange(float amount)
{
Value += amount;
}
public void ApplyChange(FloatVar amount)
{
Value += amount.Value;
}
}
StringVar.cs
using UnityEngine;
[CreateAssetMenu(fileName = "New StringVar", menuName = "Variables/StringVar")]
public class StringVar : BaseVarDef<string>
{
public void SetValue(StringVar value)
{
Value = value.Value;
}
public void ApplyChange(string amount)
{
Value += amount;
}
public void ApplyChange(StringVar amount)
{
Value += amount.Value;
}
}
Is there a way to refactor the: SetValue and the 2 overloaded ApplyChange methods into BaseVarDef.cs?
Thanks in advance