Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Is there a way to cache this function/call?

Discussion in 'Scripting' started by GonzoBonDonzo, Sep 21, 2022.

  1. GonzoBonDonzo

    GonzoBonDonzo

    Joined:
    Jul 29, 2022
    Posts:
    63
    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?

    Code (CSharp):
    1.     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)
    2.     {
    3.         if (collision.collider.gameObject.tag == "Attack") // if this object collides with the monster
    4.  
    5.         {
    6.  
    7.             damage = ap.attackpow; // "damage" will equal whatever the "attackpow" value is within ap (ap is shorthand for what we defined above)
    8.  
    9.             TakeDamage(damage); // perform the "Take Damage" function (which is below)
    10.         }
    11.     }
    12.  


    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...


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class M01Rat : MonoBehaviour // M (Monster) # (# in order) Name (Monster Name) = M01Rat. This is a specific health & reward script for a Rat monster.
    6. {
    7.     PlayerLevel pl; // declare the playerlevel script as pl, must be defined below in awake or start
    8.     CapsuleCollider2D moncollider; // declare Capsule Collider 2D as "moncollider"
    9.     EdgeCollider2D atkcollider; // declare Edge Collider 2D as "atkcollider"
    10.     Animator animator; // declare the animator
    11.     AttackPower ap; // declare AttackPower as ap
    12.  
    13.     public float maxHealth = 3.0f; // create and declare a max health float of this monster
    14.     public float health; // create another float just called health
    15.  
    16.     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.
    17.  
    18.  
    19.  
    20.     void Awake()
    21.     {
    22.         pl = GameObject.FindWithTag("Player").GetComponent<PlayerLevel>(); // declare what the pl shorthand from above actually is
    23.         moncollider = GetComponent<CapsuleCollider2D>(); // define what exactly the "moncollider" above is/points to
    24.         atkcollider = GameObject.FindWithTag("Attack").GetComponent<EdgeCollider2D>(); // define what exactly the "atkcollider" above is/points to
    25.         animator = GetComponent<Animator>(); // declare what exactly the animator equals
    26.         ap = GameObject.FindWithTag("Player").GetComponent<AttackPower>(); // define what ap actually is (in this case, script on player called "AttackPower")
    27.  
    28.         health = maxHealth; // by default, health will equal max health
    29.     }
    30.  
    31.  
    32.  
    33.     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)
    34.     {
    35.         if (collision.atkcollider) // if this object collides with the monster
    36.  
    37.         {
    38.  
    39.             damage = ap.attackpow; // "damage" will equal whatever the "attackpow" value is within ap (ap is shorthand for what we defined above)
    40.  
    41.             TakeDamage(damage); // perform the "Take Damage" function (which is below)
    42.         }
    43.     }
    44.  
    45.  
    46.  
    47.  
    48.     public void TakeDamage(float damage) // public void called TakeDamage (with the parameters being a float and the value of that float equally "damage")
    49.  
    50.     {
    51.  
    52.         health -= damage; // health of the monster is going to be minus equal to "damage", set above as ap.attackpow
    53.  
    54.         StartCoroutine(TookDamage()); // next the coroutine "TookDamage" will run
    55.  
    56.  
    57.         if (health <= 0f) // if Health is less than or equal too 0
    58.  
    59.         {
    60.             StartCoroutine(OnDeath()); // start coroutine called "OnDeath"
    61.  
    62.         }
    63.  
    64.     }
    65.  
    66.  
    67.     public IEnumerator TookDamage() // a special function, IENumerator, called TookDamage. IENumerator is a function that stores numerators/sequences, and runs those sequences in order
    68.     {
    69.  
    70.         //below instructions happen in order
    71.  
    72.         animator.SetBool("TakingDamage", true); // change the TakingDamage bool to true.
    73.         yield return new WaitForSeconds(0.1f); // we are going to wait for 1/10 of a second
    74.         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.
    75.     }
    76.  
    77.  
    78.  
    79.     public IEnumerator OnDeath() // a function that happens (on death) when other functions call it
    80.     {
    81.         //below instructions happen in order
    82.  
    83.         moncollider.enabled = false; // disable the collider
    84.         animator.SetBool("Death", true); // change the Death animator bool to true.
    85.         yield return new WaitForSeconds(1f); // we are going to wait for 1 second
    86.         Destroy(gameObject); // bye bye monster
    87.         pl.xp += 3; // playerlevel.xp (which is an integer), add equal 3 (meaning we are adding, equaling to, 3)
    88.     }
    89.  
    90.  
    91. }
     
    Last edited: Sep 21, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    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://forum.unity.com/threads/is-...ng-square-roots-in-2021.1111063/#post-7148770

    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://forum.unity.com/threads/how...form-data-into-an-array.1134520/#post-7289413

    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.
     
  3. GonzoBonDonzo

    GonzoBonDonzo

    Joined:
    Jul 29, 2022
    Posts:
    63
    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 :p
     
  4. R1PFake

    R1PFake

    Joined:
    Aug 7, 2015
    Posts:
    507
  5. GonzoBonDonzo

    GonzoBonDonzo

    Joined:
    Jul 29, 2022
    Posts:
    63
    Thanks R1P! I'll try it out
     
  6. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    524
    I realize that you didn't ask but I suggest you should reel in on the comments :) There are so many example but what could this be doing other than defining a float? Comments should add value.

    Code (CSharp):
    1. public float health; // create another float just called health
     
  7. GonzoBonDonzo

    GonzoBonDonzo

    Joined:
    Jul 29, 2022
    Posts:
    63
    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