我有一个简单的类,其中包含游戏的基本技能属性。每个玩家都有这个技能类别。我希望能够进行基本算术,例如playerSkills =playerSkills + 2,它会遍历类中的所有内容并将 2 添加到其中,或者我可能想将两个类添加在一起,例如playerSkills3 =playerSkills2 +playerSkills1。
我尝试过使用重载运算符,但在调用它们时出现堆栈溢出?
如有任何想法,我们将不胜感激。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
[Serializable]
public class PlayerSkillsClass
{
// Technical
public float speed;
public float agility;
public float jump;
public float strength;
public static PlayerSkillsClass operator *(PlayerSkillsClass multiplyThis, PlayerSkillsClass withThis)
{
PlayerSkillsClass result = multiplyThis * withThis; //...multiply the 2 Coords
return result;
}
public static PlayerSkillsClass operator *(PlayerSkillsClass multiplyThis, float withThis)
{
PlayerSkillsClass result = multiplyThis * withThis; //...multiply the Coord with the float
return result;
}
public static PlayerSkillsClass operator +(PlayerSkillsClass addThis, PlayerSkillsClass withThis)
{
PlayerSkillsClass result = addThis + withThis; //...multiply the 2 Coords
return result;
}
public static PlayerSkillsClass operator +(PlayerSkillsClass addThis, float withThis)
{
PlayerSkillsClass result = addThis + withThis; //...multiply the Coord with the float
return result;
}
}
我收到此 StackOverflow 错误,该错误对于我要添加在一起的类中的每个元素都会重复:
StackOverflowException:请求的操作导致堆栈溢出。 PlayerSkillsClass.op_Addition (PlayerSkillsClass addThis, System.Single withThis) <0x17a6a1af0 + 0x00004> in
请注意,这个课程将有数十种技能,随着时间的推移,我将添加和删除技能,所以我不想编写手动函数来对每项技能进行 1 1 的添加/乘法/减去等(我以前有过)
查看
+
运算符。您将 A + B
定义为 (return A + B
) - 但 A + B
仅使用相同的运算符,导致无限递归并最终导致堆栈溢出。
我怀疑你想返回一个新的
PlayerSkillsClass
对象,将 withThis
的值添加到每个属性:
public static PlayerSkillsClass operator +(PlayerSkillsClass addThis, float withThis)
{
return new PlayerSkillsClass {
speed = addThis.speed + withThis,
agility = addThis.agility + withThis,
strength = addThis.strength + withThis,
strength = addThis.strength + withThis
}
}