Silla Rimax
Silla Rimax

Reputation: 9

Communication between scripts is not working,

I'm doing a mechanic that if you shoot at a specific object it adds ammo, but I tried a lot of things and ammo is not being added when it collides with the object.

Here is the code:

public GlobalAmmo ammo;

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.transform.tag == "Enemy")
    {
        Destroy(gameObject);
    }
    if (collision.gameObject.CompareTag("Ammo"))
    {
        ammo.ammo += 3;
    }
}

Edit: sorry!
I already put this code and I put in the images that the "if" is working, so I don't understand why this is not working because the ammo decrease correctly. image

I think it must be a very silly mistake, I'm actually doing this project to test everything I'm learning

if (collision.transform.tag == "Ammo")
    {
        print("Hit!");
        ammo.ammo += 3;
    }

Upvotes: 0

Views: 78

Answers (2)

Pac0
Pac0

Reputation: 23174

Since your debugging shows that the if is properly executed, I see one main possibility (an easy mistake to make when not used to Unity).

Is that a script you dragged-dropped over 2 different game objects?

You are probably not modifying the proper instance of the GlobalAmmo class (script) . There might be two (or more) GlobalAmmo.

Instead you should refer to only one instance, which is the "source of truth".

For instance, during Init the public GlobalAmmo ammo; should be initialized by fetching the proper script instance if it is on another object etc.

As per your comments, it seems you figured it out! Feel free to add more details if this is not the case.

Upvotes: 0

GanzYe
GanzYe

Reputation: 23

Does the shooting itself work?

Try to write:

if (collision.gameObject.CompareTag("Ammo"))
{
    Debug.Log("Work");
    ammo.ammo += 3;
}

If you do not write "Work" on the console, then you have an error somewhere else.

Upvotes: 1

Related Questions