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

Question using Rigidbody component in an equation

Discussion in 'Scripting' started by Tacotronn0220, Feb 11, 2023.

  1. Tacotronn0220

    Tacotronn0220

    Joined:
    Oct 26, 2022
    Posts:
    2
    I'm having some trouble with some code for my game and I am doing some speed based damage calculations and I can't figure out how to round GetComponent<Rigidbody>().velocity.magnitude as it says "error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)" in the error and console section in the unity editor. does anyone have any tips or suggestions for replacements?
    Here is a section of my code I am trying to use it in.
    Code (CSharp):
    1. if(baseboostpunch && !punchdamageboost1 && !punchdamageboost2)
    2.         {
    3.             if(GetComponent<Rigidbody>().velocity.magnitude > moveSpeedbase)
    4.             {
    5.               damage = damagebase + GetComponent<Rigidbody>().velocity.magnitude - moveSpeedbase;
    6.             }
    7.             else
    8.             {
    9.               damage = damagebase;
    10.             }
    11.         }
    Thank you in advance.
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,015
    Worth reading the docs on float point numbers: https://learn.microsoft.com/en-us/d...ce/builtin-types/floating-point-numeric-types

    And this section on built in implicit and explicit conversions: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions

    Ergo, you can't convert a float to an int without explicitly casting it (because information is lost). Such as:
    Code (CSharp):
    1. int someInt = (int)someFloat;
    Also you should probably just cache the rigidbody body component at some point in your monobehaviour rather than repeated
    GetComponent<T>
    calls.
     
    Bunny83 likes this.
  3. Tacotronn0220

    Tacotronn0220

    Joined:
    Oct 26, 2022
    Posts:
    2
    This worked perfectly. Thank you for the help.