Is there a way to cache this function/call?

Hi everyone!

Here’s the code of the function, with the call in question being the first “If”. It’s working perfect right now, but I don’t want to be inefficient. Maybe I don’t need to cache it. Maybe I’m just being anal?

    private void OnCollisionEnter2D(Collision2D collision) // call Collision2D, with collision in blue being the parameter (and anytime from here on, if we using the word collision, that will be the parameter)
    {
        if (collision.collider.gameObject.tag == "Attack") // if this object collides with the monster

        {

            damage = ap.attackpow; // "damage" will equal whatever the "attackpow" value is within ap (ap is shorthand for what we defined above)

            TakeDamage(damage); // perform the "Take Damage" function (which is below)
        }
    }

I’ve already cached the attack collider in question as “atkcollider”. But attempting the “so simple it’s stupid” method of collision.atkcollider, produces a "Collision2D does not contain a definition for “atkcollider”.

Here’s the full monster script this function appears in too just in case…

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

public class M01Rat : MonoBehaviour // M (Monster) # (# in order) Name (Monster Name) = M01Rat. This is a specific health & reward script for a Rat monster.
{
    PlayerLevel pl; // declare the playerlevel script as pl, must be defined below in awake or start
    CapsuleCollider2D moncollider; // declare Capsule Collider 2D as "moncollider"
    EdgeCollider2D atkcollider; // declare Edge Collider 2D as "atkcollider"
    Animator animator; // declare the animator
    AttackPower ap; // declare AttackPower as ap

    public float maxHealth = 3.0f; // create and declare a max health float of this monster
    public float health; // create another float just called health

    private float damage; // make a private float called damage. Will be used whenever the monster gets hit by the player attack collider. No value set yet.



    void Awake()
    {
        pl = GameObject.FindWithTag("Player").GetComponent<PlayerLevel>(); // declare what the pl shorthand from above actually is
        moncollider = GetComponent<CapsuleCollider2D>(); // define what exactly the "moncollider" above is/points to
        atkcollider = GameObject.FindWithTag("Attack").GetComponent<EdgeCollider2D>(); // define what exactly the "atkcollider" above is/points to
        animator = GetComponent<Animator>(); // declare what exactly the animator equals
        ap = GameObject.FindWithTag("Player").GetComponent<AttackPower>(); // define what ap actually is (in this case, script on player called "AttackPower")

        health = maxHealth; // by default, health will equal max health
    }



    private void OnCollisionEnter2D(Collision2D collision) // call Collision2D, with collision in blue being the parameter (and anytime from here on, if we using the word collision, that will be the parameter)
    {
        if (collision.atkcollider) // if this object collides with the monster

        {

            damage = ap.attackpow; // "damage" will equal whatever the "attackpow" value is within ap (ap is shorthand for what we defined above)

            TakeDamage(damage); // perform the "Take Damage" function (which is below)
        }
    }




    public void TakeDamage(float damage) // public void called TakeDamage (with the parameters being a float and the value of that float equally "damage")

    {

        health -= damage; // health of the monster is going to be minus equal to "damage", set above as ap.attackpow

        StartCoroutine(TookDamage()); // next the coroutine "TookDamage" will run


        if (health <= 0f) // if Health is less than or equal too 0

        {
            StartCoroutine(OnDeath()); // start coroutine called "OnDeath"

        }

    }


    public IEnumerator TookDamage() // a special function, IENumerator, called TookDamage. IENumerator is a function that stores numerators/sequences, and runs those sequences in order
    {

        //below instructions happen in order

        animator.SetBool("TakingDamage", true); // change the TakingDamage bool to true.
        yield return new WaitForSeconds(0.1f); // we are going to wait for 1/10 of a second
        animator.SetBool("TakingDamage", false); // return the TakingDamage bool to false. We only need to flip this bool from true to false very briefly to activate the animation.
    }



    public IEnumerator OnDeath() // a function that happens (on death) when other functions call it
    {
        //below instructions happen in order

        moncollider.enabled = false; // disable the collider
        animator.SetBool("Death", true); // change the Death animator bool to true.
        yield return new WaitForSeconds(1f); // we are going to wait for 1 second
        Destroy(gameObject); // bye bye monster
        pl.xp += 3; // playerlevel.xp (which is an integer), add equal 3 (meaning we are adding, equaling to, 3)
    }


}

What is atkcollider?! Names of GameObjects don’t affect variable names.

Always start from the documentation, in this case for Collision2D. You’ll see it does not have an atkcollider property.

Sigh. Don’t become like that Gonzo. Just… don’t.

Standard optimization warnings:

DO NOT OPTIMIZE “JUST BECAUSE…” If you don’t have a problem, DO NOT OPTIMIZE!

If you DO have a problem, there is only ONE way to find out. Always start by using the profiler:

Window → Analysis → Profiler

Failure to use the profiler first means you’re just guessing, making a mess of your code for no good reason.

Not only that but performance on platform A will likely be completely different than platform B. Test on the platform(s) that you care about, and test to the extent that it is worth your effort, and no more.

https://discussions.unity.com/t/841163/2

Remember that optimized code is ALWAYS harder to work with and more brittle, making subsequent feature development difficult or impossible, or incurring massive technical debt on future development.

Notes on optimizing UnityEngine.UI setups:

https://discussions.unity.com/t/846847/2

At a minimum you want to clearly understand what performance issues you are having:

  • running too slowly?
  • loading too slowly?
  • using too much runtime memory?
  • final bundle too large?
  • too much network traffic?
  • something else?

If you are unable to engage the profiler, then your next solution is gross guessing changes, such as “reimport all textures as 32x32 tiny textures” or “replace some complex 3D objects with cubes/capsules” to try and figure out what is bogging you down.

Each experiment you do may give you intel about what is causing the performance issue that you identified. More importantly let you eliminate candidates for optimization. For instance if you swap out your biggest textures with 32x32 stamps and you STILL have a problem, you may be able to eliminate textures as an issue and move onto something else.

This sort of speculative optimization assumes you’re properly using source control so it takes one click to revert to the way your project was before if there is no improvement, while carefully making notes about what you have tried and more importantly what results it has had.

Aye… Thanks Kurt.

You are right, I shouldn’t even worry about it. “Fix it until it’s broke” is what I’m doing.

I knew why I was getting the error of “Collision2D does not contain…”, I was just confused because I thought I had cached what “atkcollider” was (and except that to be inserted when used).

I’m not experiencing any issue that I would call performance related. It’s just a simple case of being anal :stuck_out_tongue:

One simple thing you could “optimize” is to use the CompareTag method, you will most likely not notice any performance difference at this point, but the methoed was intended to be used to compare tags and it doesn’t make the code more complicated Unity - Scripting API: Component.CompareTag

Thanks R1P! I’ll try it out

I realize that you didn’t ask but I suggest you should reel in on the comments :slight_smile: There are so many example but what could this be doing other than defining a float? Comments should add value.

public float health; // create another float just called health

I know that comments should be used to only tell other programmers what your code is doing (and all programmers should understand what a float declaration is), I’ve decided to comment on everything I do, for continuing learn/understanding purposes