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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

how can I invoke a void with variable?

Discussion in 'Scripting' started by Kertaix, Aug 15, 2022.

  1. Kertaix

    Kertaix

    Joined:
    Jul 19, 2022
    Posts:
    33
    Hello

    I have this statement,
    Invoke(nameof(TakingDamage(enemyTag.enemyStrength)), 0.15f);

    which doesn't work. (error CS8081: Expression does not have a name)
    btw. enemyTag.enemyStrength is a int variable.

    So how can I invoke this?

    Do I have to invoke an other void in which I just write
    TakingDamage(enemyTag.enemyStrength);
    to be able to do this with a time delay?
    I guess it would work but that's cumbersome.
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,003
    Monobehaviour.Invoke is probably what I would consider bad practice.

    It'd be easier to learn to use coroutines.
     
    JoNax97 and Bunny83 like this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,571
    I know it's a pointless fight, but first of all: You can not invoke "a void". You can invoke "a void method". "void" is just a pseudo type and in the context of a method declaration defines the return type of the method.

    Your code does not make sense syntactically because you have to understand 2 fundamental things here:
    1. The Invoke method is a method that takes 2 arguments. The first argument is a string that indicates the method that should be called. The second (optional) argument is a delay. This method can only invoke methods that take no arguments themselfs. There is no way to pass any arguments to the invoked method when you use Invoke.
    2. The "nameof" operator of the C# language can turn any identifier in the context of C# into a string. So using
      nameof(TakingDamage)
      would be directly replaced by
      "TakingDamage"
      . The only advantage using nameof is, that refactoring the method name would also catch the name inside the nameof operator since it directly refers to the identifier within the C# context.
    Like Spiney said, what you want to do is done the easiest way using a Coroutine. You can simply add a utility script like this to your project:

    Code (CSharp):
    1. // DelayedCall.cs
    2. using UnityEngine;
    3.  
    4. public class DelayedCall : MonoBehaviour
    5. {
    6.     private static DelayedCall m_Instance = null;
    7.     public static DelayedCall GetInstance()
    8.     {
    9.         if (m_Instance == null)
    10.         {
    11.             m_Instance = (new GameObject("DelayedCall")).AddComponent<DelayedCall>();
    12.             DontDestroyOnLoad(m_Instance.gameObject);
    13.         }
    14.         return m_Instance;
    15.     }
    16.     public static Coroutine Run(System.Action aCallback, float aDelay)
    17.     {
    18.         return GetInstance().StartCoroutine(CallAfter(aCallback, aDelay));
    19.     }
    20.     static IEnumerator CallAfter(System.Action aCallback, float aDelay)
    21.     {
    22.         yield return new WaitForSeconds(aDelay);
    23.         aCallback();
    24.     }
    25. }
    With this class in your project you can simply use

    Code (CSharp):
    1. DelayedCall.Run(()=>TakingDamage(enemyTag.enemyStrength), 0.15f);
     
  4. Kertaix

    Kertaix

    Joined:
    Jul 19, 2022
    Posts:
    33
    Thank you

    I have to admit, I didn't (and still not completly) understand your code so I went and watched some tutorials and came up with this:
    Code (CSharp):
    1. private void OnTriggerEnter2D(Collider2D coll)
    2.     {
    3.  
    4.         //enemyCollision
    5.         if (coll.gameObject.CompareTag("Enemy"))
    6.         {
    7.             enemyTag = coll.gameObject.GetComponent<EnemyConnecter>().enemyToConnect;
    8.             if (enemyTag != null)
    9.             {
    10.                 StartCoroutine(TakingDamage(enemyTag.enemyStrength));
    11.             }
    12.             else
    13.                 Debug.Log("Enemy has no EnemySO or EnemyConnecter");
    14.  
    15.            
    16.         }
    17.     }
    18.  
    19.     //enemyCollision
    20.     IEnumerator TakingDamage(int enemyStrength)
    21.     {
    22.         yield return new WaitForSeconds(0.15f);
    23.         if (!isInvincible)
    24.         {
    25.             lifeCount -= enemyStrength;
    26.             takenDamage = true;
    27.         }
    28.        
    29.     }
    30.  
    which is working the way I want it to. But as I'm new to this. Is this going to cause me problems? I don't have a lot of the stuff you wrote in your code...


    I'm still going to try to comletly understand your code but I quickly have to ask a basic question:
    Can I write this in the class I already have?

    Thanks for your time
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,946
    Sounds like perhaps you failed to do Step #2 of tutorial / example code?

    Since it's the only step that actually counts in this whole process, I'll repost it here for you:

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.


    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!
     
  6. Kertaix

    Kertaix

    Joined:
    Jul 19, 2022
    Posts:
    33
    Thanks but I don't know wether I unerstand you correctly or vice versa.

    The code I posted doesn't cause me any errors, it's working and does exactly what I want it to do. What I am wondering about is wether this is a good approach as the example code of Bunny83 has way more stuff.

    I could also explain it to my cat as in step 2, as a mather of facts I'm somewhat stubborn and much rather start with step 2 and only circle back to step 1 if it wont work out. For the code I wrote I completle understand the logic and what it does, I just don't know if this logic is clever for this situation.

    For the code of Bunny83 I do still work on step 2.


    On a sidenote, some time ago you told me I should create debug log statments for nullRefs. The thing I wrote on line 13, is that what you ment?
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,946
    Line 13 is beautiful! I approve of every character contained in line 13. Programs written like that are a dream to work on because when you forget something a year or two into the future, you instantly know what went wrong.
     
    Kertaix likes this.
  8. JoNax97

    JoNax97

    Joined:
    Feb 4, 2016
    Posts:
    611
    Your code is fine. The code that Bunny83 posted is more complex because it's meant to be reusable. Instead of writing the same(ish) code every time you need a delay, what they did was make a self-contained component that adds a delay to any code and a handy way of accessing it.

    If you want to learn how it works, 2 keywords to Google are "singleton pattern" and "delegates".

    But if you don't need all that right now, know that your code is a-ok and just move to the next problem at hand. You can always revisit this later.

    Good luck!
     
    Kertaix likes this.