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
  4. Dismiss Notice

Question ❤️break, I can't find a solution for C# attribute feature!

Discussion in 'Scripting' started by Landa-100, Oct 7, 2023.

  1. Landa-100

    Landa-100

    Joined:
    Sep 9, 2018
    Posts:
    17
    Code (CSharp):
    1.  /***/
    2.     [Alive(nameof(isAlive))]
    3.     // This function is use for Input System callback only
    4.     void OnJump(InputValue value)
    5.     {
    6.         // if (!isAlive) return;
    7.  
    8.         if (value.isPressed)
    9.         {
    10.             if (isGround && !isJump)
    11.             {
    12.                 rb.velocity += new Vector2(0f, jumpSpeed);
    13.                 PlayAnimation("jump");
    14.                 isJump = true;
    15.             }
    16.             else
    17.             {
    18.  
    19.             }
    20.         }
    21.     }
    22.     [Alive(nameof(isAlive))]
    23.     /// This function is use for Input System callback only
    24.     void OnClimb(InputValue value)
    25.     {
    26.         // if (!isAlive) return;
    27.         // logic here
    28.     }
    Today I took all day to search for this solution, I have no any clue!

    I have a character with many animations, before playing each one, I have to check my hero is still alive before the ongoing code logic!
    So, I hope to replace this line below
    Code (CSharp):
    1. if (!isAlive) return;
    to
    Code (CSharp):
    1.  
    2.  [Alive(nameof(isAlive))]
    3.  
    Anyone can help me to write the Attribute class for this demand?
    Code (CSharp):
    1. /// <summary>
    2. ///  If the first parameter is true, the method will continue execution
    3. /// </summary>
    4. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    5. public class AliveAttribute : Attribute
    6. {
    7.     string fieldName;
    8.  
    9.     public AliveAttribute(string fieldName)
    10.     {
    11.         this.fieldName = fieldName;
    12.     }
    13. }
     

    Attached Files:

    Last edited: Oct 8, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    Looks like AliveAttribute is is part of a bigger system. Did you look in the docs for that system?


    Usually that's all you put in an attribute class. It's just a marker to label parts of your assembly.

    The actual work is done elsewhere in a class that looks for these tags and does things.


    What you describe (a health system) doesn't need attributes. Just go try out any one of the thousands of "add health" tutorials for Unity.

    It will be a scalar value (such as int or float) and some methods to manipulate it and make decisions about it. That's it. Everything above that is extra credit implementation details.


    For future reference:

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    - Do not TALK about code without posting it.
    - Do NOT post unformatted code.
    - Do NOT retype code. Use copy/paste properly using code tags.
    - Do NOT post screenshots of code.
    - Do NOT post photographs of code.
    - ONLY post the relevant code, and then refer to it in your discussion.


    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!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.
     
  3. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,085
    Why?

    I don't see the point in doing so. It would only complicate an otherwise trivial if condition.

    Actually, since you are using the new Input System you should look into how action maps work. Basically you'd have a map for Alive and one for Dead and another for Menu and at the given time, you switch maps. The Dead actions obviously wouldn't include input for interacting with the character.
     
  4. Landa-100

    Landa-100

    Joined:
    Sep 9, 2018
    Posts:
    17
    Sorry! Let me explain more game logic.

    The scenario is an "Aspect of Programming" that I found in my character class. if I have 10 actions of character animation, which were bound to the New Input System. such as (OnMovement, OnJumpping, OnRunning ....)

    Before playing each character animation, I have to check to private state of the character class, this is where
    Code (CSharp):
    1. if (!isAlive) return;
    came from.

    I hope to find a solution to manage the state logic of my character uniformly in order to play animations correctly.

    The fundamental concept is interception ❤️
    https://github.com/dotnet/roslyn/blob/main/docs/features/interceptors.md
     
    Last edited: Oct 8, 2023
  5. Landa-100

    Landa-100

    Joined:
    Sep 9, 2018
    Posts:
    17
    Thank you I will post my code in text format later. I have researched many topics on Google, videos on YouTube, and Microsoft C# Docs, and it's hard to find a solution...
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    Really??

    If you Destroy() the player GameObject itself you can simply check if the reference is null to decide if he's dead.

    Code (csharp):
    1. if (myPlayerInstance == null)
    2. {
    3.   Debug.Log( "Player is dead.");
    4. }
    And then when you kill the player:

    Code (csharp):
    1. Destroy( myPlayerInstance);
    It's that easy.
     
    Landa-100 likes this.
  7. Saniell

    Saniell

    Joined:
    Oct 24, 2015
    Posts:
    168
    There is no real problem to solve, all you're doing is overengineering for no reason
     
  8. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,085
    Not really.

    When the player dies, you simply switch the Input Action map to "No Input". You assign no input to that map, except perhaps a key to bring up the menu or restart the level or whatever. Then you cannot get any input that triggers jumping, climbing, moving animations (or behaviour) and thus there is no need to add conditionals that check whether the player is alive or dead.

    Of course when the player respawns the Action map needs to be set back to the regular input map.
     
    Landa-100 likes this.
  9. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,539
    I don't think you understand what attributes actually are. All Attributes have NO functionality at all, ever. Attributes are pure metadata and are stored as such directly in the assembly. It's literally the memory footprint of the attribute type that is impinted in the assembly.

    Attributes can only be read via reflection. So whatever system may use / react to attributes have to use reflection to check and read the content of attributes. Of course most systems would usually analyse the types and members once and cache the necessary information for later use. Unity most likely does something similar with all of its "magic" callbacks, but on the native C++ side.

    So in your case, the question is who / from where is that method called? That caller has to check the attribute and react accordingly. There are other systems ( like Unity's network code ) which post process the compiled code and "weave" in extra code depending on the used attributes.

    From your posted details it's not really clear how that "feature" should work. With post processing all sorts of things are possible. Like renaming the actual method to an internal name and creating a new wrapper method that does the check before calling the internal method or directly weave in the check at the start of the method. However such postprocessing stuff is not that trivial.

    Unity has now support for code analyzers and code generators. So you may want to look into those?
     
    CodeSmile likes this.
  10. Landa-100

    Landa-100

    Joined:
    Sep 9, 2018
    Posts:
    17
    Yes, I can check the logic from InputSystem layer before those Animations were called. Good solution!!! Thank you!
     
  11. Landa-100

    Landa-100

    Joined:
    Sep 9, 2018
    Posts:
    17
    You are correct, the .NET Attribute feature is a kind of code comment, and it is hard to implement AOP in a few lines of code.
    Now .NET 8 has released a preview feature that can simplify the AOP process.
    Code (CSharp):
    1. using System;
    2. using System.Runtime.CompilerServices;
    3.  
    4. var c = new C();
    5. c.InterceptableMethod(1);
    6. c.InterceptableMethod(2);
    7.  
    8. class C
    9. {
    10.     public void InterceptableMethod(int param)
    11.     {
    12.         Console.WriteLine($"interceptable {param}");
    13.     }
    14. }
    15.  
    16. static class D
    17. {
    18.     [InterceptsLocation("C:\\Users\\Administrator\\source\\repos\\ConsoleApp5\\Program.cs", line: 5, character: 3)]
    19.     public static void InterceptorMethod(this C c, int param)
    20.     {
    21.         Console.WriteLine($"interceptor {param}");
    22.     }
    23.  
    24.     [InterceptsLocation("C:\\Users\\Administrator\\source\\repos\\ConsoleApp5\\Program.cs", line: 6, character: 3)]
    25.     public static void OtherInterceptorMethod(this C c, int param)
    26.     {
    27.         c.InterceptableMethod(99); //run before InterceptableMethod
    28.         Console.WriteLine($"other interceptor {param}");
    29.         c.InterceptableMethod(100);//run after  InterceptableMethod
    30.     }
    31. }
    32.  
    The output:
    interceptor 1
    interceptable 99
    other interceptor 2
    interceptable 100

    Hopefully, Unity will support latest .NET features as soon as possible.