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

Using a function in another scrip to add force

Discussion in 'Scripting' started by unity_xe9PBv2gWDDgAg, May 7, 2020.

  1. unity_xe9PBv2gWDDgAg

    unity_xe9PBv2gWDDgAg

    Joined:
    Apr 23, 2020
    Posts:
    1
    Hi there, I'm trying to use a hovering function I've made in another script on this object, when I try to use it, I get the error "An object reference is required for the non-static field, method or property".

    The function:
    Code (CSharp):
    1.    private Vector3 AbsoluteUp = new Vector3 (0f, 1f, 0f);
    2.  
    3.  
    4.     public void HoverFunction(Rigidbody ThisRB, Vector3 position,float HoverHeight, float Sensitivity, float MaxThrust)
    5.     {
    6.         Ray HeightMeasure = new Ray(position, -AbsoluteUp);
    7.         RaycastHit hit;
    8.         float mass = ThisRB.mass;
    9.  
    10.         if (Physics.Raycast(HeightMeasure, out hit))
    11.         {
    12.             if (hit.distance < HoverHeight)
    13.             {
    14.                
    15.                 float HeightDelta = HoverHeight - hit.distance;
    16.                 float HoverForce = (HeightDelta / (Mathf.Sqrt(Mathf.Pow(HoverHeight, 2) + Sensitivity * MaxThrust * mass)));
    17.                 Vector3 HoverForceV3 = new Vector3(0, HoverForce, 0);
    18.                 ThisRB.AddForceAtPosition(HoverForceV3, position);
    19.             }
    20.         }
    21.     }

    Trying to use it:
    Code (CSharp):
    1.         Vector3 position = transform.position;
    2.  
    3.         NewFunctionsTest.HoverFunction(rb, position, 5f, 3f, 15f);
    Variable rb was defined as the current components rigidbody (which it has). Excluded for brevity. I'm quite new to Unity so feeling a bit lost!
     
  2. sbalanoff

    sbalanoff

    Joined:
    Nov 14, 2019
    Posts:
    36
    Are you sure that you have assigned the "NewFunctionsTest" in the inspector (or via script)?
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    You just need to mark HoverFunction as a static method.
    Code (CSharp):
    1. public static void HoverFunction...