-3

I'm a beginner and I need some help to pass a function located on one script to another one so I can use his value. First I have a class called Enemies where I count the enmies killed and then I have a script that allows the player to go to the next level using a door. So I want to use the counter to "open" the door when the player has killed X number of enemies. How can I pass the counter value? Thanks.

public class Enemies : MonoBehaviour {

    public GameObject enemy;
    public int health = 100;
    public int deathCounter = 0;

    public void TakeDamage(int damage)
    {
        health -= damage;
        if (health <= 0)
        {

            Destroy(enemy);
            deathCounter++;
        }
    }
}

public class nextlevel : MonoBehaviour {
    public Enemies deadcounter;
    public int index;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.CompareTag("Player"))
        {

            SceneManager.LoadScene(1);

        }    
    }     
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
mone
  • 27
  • 1

1 Answers1

1

For that you need a reference to your script. Here are two easy ways to get one:

1) Create a public variable and assign it in the inspector

You can create a public variable of type Ennemies or create a private variable and serialize it.

public Ennemies yourScript;

or

[SerializeField]
private Ennemies _yourScript;`

Then, you should see an empty reference to your script in the inspector. Simply drag the GameObject containing your script in the empty slot and it will automatically create a reference to the script.

Empty component

Assigned component


2) Extract the component from a GameObject in your script

Using GetComponent<>() you can extract your script from a GameObject that contains it. You can get a reference to that object through children, parents or using the first method.

GameObject ennemy;
Enemies yourScript;

yourScript = ennemy.GetComponent<Enemies>();

Get the value from your script

Once you have a reference to your script, you can simply access the value as a property of the variable storing the script. deathCounter is a public variable, you can read and modify it anywhere, at any time.

int counter = yourScript.deathCounter;  
Savaria
  • 565
  • 4
  • 12