Search Unity

C# - Error CS0120

Discussion in 'Scripting' started by HorrorGameDev, May 27, 2018.

  1. HorrorGameDev

    HorrorGameDev

    Joined:
    Nov 4, 2017
    Posts:
    5
    Hey, everyone. So, I have this problem in one of my game's scripts that is generating the following error.

    Unity Version: 3.4.0

    Code (CSharp):
    1. error CS0120: An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)'
    Here's the code that's generating the error:

    Code (CSharp):
    1. public void Update(Victim victim)
    2.     {
    3.         if (this.follow.HasReachedTarget() && !this.hasStartedToUse)
    4.         {
    5.             this.hasStartedToUse = true;
    6.             Victim.StartCoroutine(this.AnswerThePhone(new Victim()));
    7.         }
    8.     }
    Programming is not really my strong suit, so if anyone could help me on this, it would be much obliged. Please and thank you!

    - HorrorGameDev
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    Hi, if I may go through a few points :

    First, you are calling the method on the class, not on the object that you have handed into Update().

    So you need to change Victim.StartCoroutine (on line 6) to this victim.StartCoroutine. Notice the capitalisation of the "V". This switches from calling on the class (Victim) to calling on the object (victim) in this case.

    Second, I would be inclined to name your Update method something else. It looks like the Unity method but isn't. I could easily imagine that becoming quite confusing. :)

    Third, you are starting a Coroutine via victim, that is running a function in this object that takes a Victim object as a parameter. Now, I'm not sure off the top of my head if that will cause any weird side effects or not. Whilst my suspicion is that it will work ok, the object interaction there is a little, shall we say, convoluted. Is it possible to make that a little tidier? :)
     
    Bunny83 and arktos888 like this.
  3. Elementalist_

    Elementalist_

    Joined:
    Dec 9, 2020
    Posts:
    6
    I have a similar problem. I get the error from accessing a public dynamic variable from a dynamic method (void Update()), so, how do I fix that?
    Orbs script contains:
    Code (CSharp):
    1. public int orbsLeft = 0;
    Another script:
    Code (CSharp):
    1. void Update()
    2.     {
    3.         if (Orbs.orbsLeft != 0)
    4.         {
    5.  
    6.         }
    7.     }
     
    Last edited: Nov 8, 2021
  4. uwdlg

    uwdlg

    Joined:
    Jan 16, 2017
    Posts:
    150
    Not sure what you mean by dynamic in this context, but if you're also getting error CS0120, that would mean you're probably trying to use the non-static field
    orbsLeft
    using the class name before the . (
    Orbs
    in line 3 in
    Update()
    ). Instead, you need a variable containing an instance of the class with the
    orbsLeft
    field before the . , e.g.
    variable
    in this example:
    Code (CSharp):
    1. ClassName variable = new ClassName();
    2. // ...
    3. if (variable.orbsLeft != 0) {
    4.     // do something
    5. }
    where ClassName needs to be the name of the class containing
    orbsLeft
    (presumably
    Orbs
    in your case). If that class extends MonoBehaviour, you can't use the constructor as in my example, but rather use a public /
    [SerializeField] private
    field in the other script with the Update method into which you can drag and drop a reference to an instance of the
    orbsLeft
    class on a GameObject in the editor.
     
  5. Cyron113

    Cyron113

    Joined:
    Aug 18, 2022
    Posts:
    1
    Same problem! I tryed to call "public void Interacted(int behav)" from "Interact" sript to "InteractionController" sctript, but I got the message:
    Assets\Sripts\Interactions\InteractionController.cs(35,21): error CS0120: An object reference is required for the non-static field, method, or property 'Interact.Interacted(int)'

    here's the Interact sript:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Interact : MonoBehaviour
    6. {
    7.     public GameObject PickupPosIndicator;
    8.     public Vector3 PickupPos;
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.         PickupPos = PickupPosIndicator.transform.position;
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.      
    19.     }
    20.     public void Interacted(int Behav)
    21.     {
    22.         //My code
    23.     }
    24. }
    And the InteractionController:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class InteractionController : MonoBehaviour
    6. {
    7.     [SerializeField] private float range;
    8.     [SerializeField] private Camera cam;
    9.     [SerializeField] private LayerMask mask;
    10.     private GameObject interactedObj;
    11.  
    12.  
    13.     public List<GameObject> interactables;
    14.  
    15.     public GameObject cube;
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.         cam = GetComponent<CaracterController>().playerCamera;
    20.      
    21.     }
    22.  
    23.     // Update is called once per frame
    24.     void Update()
    25.     {
    26.         Ray ray = new Ray(cam.transform.position, cam.transform.forward);
    27.             Debug.DrawRay(ray.origin, ray.direction * range);
    28.         RaycastHit hit;
    29.         if (Input.GetMouseButtonDown(1) && Physics.Raycast(ray, out hit, range, mask)) {
    30.             if(hit.collider.GetComponent<Interact>() != null)
    31.             {
    32.                 if(hit.collider == interactables[0])
    33.                 {
    34.                     cube.GetComponent<Interact>();
    35.                     Interact.Interacted(0);
    36.                 }
    37.             }
    38.         }
    39.     }
    40. }
    If anyone can help me, please tell me how do I get rid of the error, or where can I find a f***n tutorial for raycast interactions, that already actualy works!
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Please stop necro-posting to old threads for simple typing mistakes.

    Instead, go back to the tutorial where you got the above from and slow down and check your work over. You have clearly made a mistake. This will guide to finding the mistake:

    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.

    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.

    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... start back at the top of this post!
     
    Cyron113 and Agoston_R like this.
  7. Agoston_R

    Agoston_R

    Joined:
    Mar 30, 2022
    Posts:
    13
    If you're new to C# and programming in general then static vs instance variables can be confusing. I found some good explanations on StackOverflow that explain the differences and include best practice tips to use them.