Combat System

Hello,

I am trying to make a combat system and it’s not working the way I want. My main current issue is that the value of my variables are not found by the combat method. It’s probably basic stuff but I think that solving this issue would help me for a lot of other things.

Here my code so far:

In script A I have:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScriptA : MonoBehaviour
{
    // declaring enemy stats variable

    private int enemyLife = 0;
    private int enemyDamage = 0;
    private int enemyAgility = 0;

    int getDamage = Stats.damage;


    // Various enemys made of methods
    public void necro()
    {
       combatMethod(50, 20, 10);
    }

    public void dragon()
    {
        combatMethod(100, 30, 15);

    }

    // My combat method used by every enemys
    public void combatMethod(int enemyLife, int enemyDamage, int enemyAgility)
    {
        enemyLife = enemyLife - getDamage;
    }
}

And Script B calling a monster

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;



public class ScriptB : MonoBehaviour
{
    public ScriptA _combatScript;


    public void Attack()
    {
        _combatScript.necro();
    }
}

I tried to make “combatMethod();” as an OnClick event on a button. But it is not working when it has the “int enemyLife, int enemyDamage, int enemyAgility” thing. And I tried alternative way but in the end whenever I click the button it does not take the value from Necro or Dragon but the base value in the ScriptA. I did not find a way to make it work. Do you have an idea ?

Thank you

That is not how function arguments work.

When you declare a function with arguments like “public void MyFunc(int x, float y)” that creates local variables called “x” and “y” that only exist inside of that one function. If you have class variables with the same names, the class variables are hidden by the local variables, and those names refer to the local variables inside the function (even though they still refer to the class variables outside of the function).

So your current “combatMethod” function creates three local variables, sets the value of one of them based on the other two, and then throws all of them away when the function is over (local variables always get thrown away when the function is over).

If you want the function to read and write the class variables, just get rid of the arguments! Functions inside your class have access to all class variables by default and you don’t need to do anything special, just use them by name.

2 Likes