我正在尝试为游戏生成方程式。
我为等式中的每个术语创建了一个类:
[System.Serializable]
public class EquationTerm
{
public int Value { get; set; } //random int between 1 and 9
public int Sign { get; set; } //1 for +, 2 for -, 3 for *, 4 for /
public bool IsNextTerm { get; set; }
//default positive equationTerm
public EquationTerm(int value)
{
Value = value;
Sign = 1;
IsNextTerm = false;
}
public EquationTerm(int value, int sign, bool nextTerm)
{
Value = value;
Sign = sign;
IsNextTerm = nextTerm;
}
}
然后我创建了两个数组来保持等式的左侧和右侧。我想使用InitializeArray函数使用我的构造函数生成两个数组,除了我不能使用它们,因为它们都有参数。 有没有办法解决这个问题?
public class EquationGenerator : MonoBehaviour
{
EquationTerm[] LeftTerms;
EquationTerm[] RightTerms;
void Start ()
{
//Initialize both side with a random number of terms
LeftTerms = InitializeArray<EquationTerm>(Random.Range (1, 6));
RightTerms = InitializeArray<EquationTerm>(Random.Range (1, 6));
}
EquationTerm[] InitializeArray<EquationTerm>(int length) where EquationTerm : new()
{
EquationTerm[] array = new EquationTerm[length];
array [0] = new EquationTerm (Random.Range (1, 10));
for (int i = 1; i < length; ++i)
{
array[i] = new EquationTerm (Random.Range (1, 10), Random.Range (1, 5), true);
}
return array;
}
我在另一篇文章中看到我可以使用Activator.CreateInstance所以我试着写
array[0] = (EquationTerm)Activator.CreateInstance(typeof(EquationTerm), new object[] { EquationTerm (Random.Range (1, 10)) });
但它告诉我Activator不存在。
答案 0 :(得分:0)
为什么不尝试使用非通用版本:
public class EquationGenerator
{
EquationTerm[] LeftTerms;
EquationTerm[] RightTerms;
void Start()
{
//Initialize both side with a random number of terms
LeftTerms = InitializeArray(Random.Range(1, 6));
RightTerms = InitializeArray(Random.Range(1, 6));
}
EquationTerm[] InitializeArray(int length)
{
EquationTerm[] array = new EquationTerm[length];
array[0] = new EquationTerm(Random.Range(1, 10));
for (int i = 1; i < length; ++i)
{
array[i] = new EquationTerm(Random.Range(1, 10), Random.Range(1, 5), true);
}
return array;
}
}