I have a simple class that contains basic skill attributes for a game. Each player has this skills class attached. I’d like to be able to do basic arithmetic, e.g. playerSkills = playerSkills + 2, and it would go through and add 2 to everything within the class, or perhaps I’d want to add two classes together like playerSkills3 = playerSkills2 + playerSkills1.
I’ve tried using overload operators but I get a stack overflow when calling them?
Any thoughts would be much appreciated.
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;
}
}
I get this StackOverflow error, which is repeated for every element in the class i’m adding together:
StackOverflowException: The requested operation caused a stack overflow.
PlayerSkillsClass.op_Addition (PlayerSkillsClass addThis, System.Single withThis) <0x17a6a1af0 + 0x00004> in
Note that this class will have dozens of skills and I’ll be adding and removing skills over time so I don’t want to write manual functions to add/multiple/subtract etc every skill 1 by 1 (I had that before)
David Martin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.