I have this code, inside this scriptable object i have int damage, how do i change this value depending on damage type enum?
public class ItemSO : ScriptableObject
{
public TileBase tile;
public Sprite image;
public int damage;
public ItemType type;
public Damage Damage;
public Speed Speed;
public ActionType actionType;
public Vector2Int range = new Vector2Int(5, 4);
public bool stackable = false;
}
public enum ItemType
{
Laser,
Engine
}
public enum ActionType
{
laser,
engine
}
public enum Damage
{
LG1 = 50,
LG2 = 100,
LG3 = 150,
not_laser = 0
}
public enum Speed
{
EG1 = 10,
EG2 = 15,
EG3 = 20,
not_engine = 0
}
public int GetDamage()
{
int damageTypeValue = (int)Damage;
return damage * damageTypeValue;
}
But this seems completely redundant when you could just changed the serialized damage value. Why does this value have to be different based on an arbitrary enum?
Having two fields that only differ by a capital letter is also a terrible idea.
Add int totalDamage = 0; just before the for loop.
If that code compiles, then totalDamage must be a variable that already exists in your class. You need totalDamage to be a local variable that is initialised to 0.
There are C# guidelines for naming your variables so that it’s easier to avoid this problem. For instance, _privateVariable, PublicVariable and localVariable.
GetComponentInChildren is also a very expensive function. You may want to modify InventorySlot to contain a reference to its InventoryItem so you don’t need to find it each time.
Ive added total damage int before for loop. But i get strange numbers, when i add item to inventorySlots[0] it prints out 300 in debug log, when it should be 100 for 1 item
The easiest way to understand what is happening is to step through the code with a debugger. You can place a breakpoint on the first line inside your GetDamage function and see how the values of each variable change as you step through it. You should be able to find which line is not doing what you expect much more easily than by adding Debug.Log statements everywhere.
This link has guides for getting started with a debugger for Visual Studio, VSCode and Jetbrains Rider.
Also, it’s good that you’re checking if itemSlot != null before accessing it. You may need to check if slot != null as well unless you’re absolutely sure that it will be there. Null checks are not free in terms of performance, but when you’re starting out it’s better to be safe. You may also want to handle the case when something is null when it shouldn’t be, such as by throwing an exception or returning an error value.