i’ve assigned class information (a name and strength value) to 2 scriptable object, I then used a different scriptable object to hold those “Classes” in an array.
Using my script im capable of switching between those two classes by pressing the space button.
The thing is when i switch to a class I add the new classes strength value to the players strength value but when I switch to a different class I’m still using the previous str value, switching repeatedly gives me infinite Strength, how do i fix this?
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
public int wantedIndex;
public Text text;
public ClassArray classArray;
public int Strength;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
wantedIndex++;
NextClass();
}
}
void NextClass()
{
int currentClassIndex = wantedIndex % classArray.baseClasses.Length;
string currentClassName = classArray.baseClasses[currentClassIndex].Name;
int currentCLassesStrength = classArray.baseClasses[currentClassIndex].Str;
Strength += currentCLassesStrength;
text.text = $"Current class Name: {currentClassName}, Strength value is {Strength}";
}
}
Integer modulo division. He’s cycling through the available things, then back to zero.
@Quiet_Apples_Studios : BUT: you should do the increment in the NextClass() method and you should also modulo-wrap the base number, because otherwise it will become negative, and when you do modulo division on a negative number, you will be unpleasantly surprised.
You want to think of it as a diagram:
base strength
any and all mods
any other realtime changes
these feed into a system that gives you an “effective strength” that is never stored anywhere, just computed from the above.
Your code allows wantedIndex to grow unbounded. After about 2 billion iterations it will wrap to a huge negative number and make your % modulo computation wrong. It would take a LONG time to do that many iterations, but it’s still a bug waiting to happen.
By wrap it I mean iterate up from 0 to the max, then reset it to 0. That way it never can be negative.