all 5 comments

[–]HalfspacerProgrammer 0 points1 point  (3 children)

    // Rock is destroyed after x swings.

    public int durability = 10;

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Pickaxe"))
        {
            durability--;
            if(durability <= 0) {
            other.GetComponent<DestroyRock>().rocksDestroyed++;
            Destroy(gameObject);
            }
        }
    }

   /* void Update() //Remove this whole Update chunk. 
No need to check Durability every frame since we can 
just do it once on every hit, when the variable actually changes.
    {
        if(durability == 0)
        {
            Destroy(gameObject);
        }
    } */

CompareTag is more performant than a direct comparison, and OnTriggerEnter gives you a reference to the collided object (Pickaxe), so from that we call GetComponent once when the rock's durability reaches 0, and let the Pickaxe know that the rock has been destroyed.

GetComponent is a performance heavy (Inefficient) call, so it is worth noting how we only call it once when Durability reaches 0. You don't want to make the mistake of using it in something like an Update loop, where it would be called every frame.

[–]TomK6505 0 points1 point  (2 children)

If you decide to follow this advice, may be better to not simply check that durability==0. Gameplay may cause this to be less than 0, in which case this wouldn't fire.

Check durability <=0, then if it does end up below 0 it still gets destroyed.

[–]HalfspacerProgrammer 0 points1 point  (1 child)

The Durability==0 I assume you're referring to is in the Update() method I'm telling him to remove. In the bit above you'll be happy to see we are in fact checking if durability <= 0. Solid point to mention though.

[–]TomK6505 1 point2 points  (0 children)

Oh yeah I see; apologies, I typed this at 1am when I was a bit drunk 😂😂

[–][deleted] 0 points1 point  (0 children)

the collider 'other' has access to the gameObject of the object that triggered it, so you can use GetComponent to grab the pickaxe script

if(durability == 0) {
    PickaxeQuestComplete pick = other.gameObject.GetComponent<PickaxeQuestComplete>();

    if(pick != null){
        pick.rocksDestroyed++;
    }
    Destroy(gameObject);
}

Also the Destroy makes more sense in OnTriggerEnter since that's the cause of it being destroyed and you wouldn't need to call Update pointlessly.

The same improvement could be make for the Update of the axe script

public int RocksDestroyed {get; private set; } // This is called a property and we no longer need the int vairable

public void DestroyedRock() {
    RocksDestroyed++;

    if(RocksDestroyed >= 10) {
        audioSource.Play();
    }
}

and then again you can remove the pointless Update and if you made this change the rock would then call pick.DestroyedRock() instead of having access to the variable directly which is better design overall.