So, here is the basic problem: value type versus reference type. For more details, read:
Value vs Reference Types in C#[
^]
When you pass a value type (e.g.
int
) like
num
or
tree.life
as a parameter, you are passing a
copy of that value. In your method (
Attack
), you are then decrementing the
copy of the value (
targetlife
),
not the original. When you return from the
Attack
method, that copy (
targetlife
) passes out of scope and is discarded.
In modern versions of C#, it is possible to pass a value type, by reference, using the
ref
or
out
keyword. For details, see the following links:
ref (C# Reference) | Microsoft Docs[
^]
out parameter modifier (C# Reference) | Microsoft Docs[
^]
However, in your case, there may be additional considerations. While the source code is not shared, I suspect
life
may be a property. Regrettably, it is not currently possible to pass a property using the
ref
/
out
keyword.
So, I would consider slightly re-modeling your
Sprite
class, which is common to both
gigel
and
tree
. In your code, it seems that
gigel
is attacking
tree
, so the method signature for
Attack
should probably more closely resemble this action.
I would suggest you change the method signature of
Attack
as follows:
public void Attack(Sprite target) =>
target.life -= damage;
Then, to have a
gigel
attack a
tree
, you would do the following:
gigel.Attack(tree);