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

Error CS0120 - An object reference is required to access non-static member

Discussion in 'Getting Started' started by Kettlewell, Jul 1, 2015.

  1. Kettlewell

    Kettlewell

    Joined:
    Jun 24, 2015
    Posts:
    19
    I'm having a wee bit of a problem with a piece of my code, I'm creating an instance of a class then attempting to use GetComponent to retrieve the game object but it gives me this error;
    FPSMouseLook is not assigned to any gameobject and it is derived from ScriptableObject. FPSControls then calls FPSMouselook by initiating an instance of FPSMouseLook class throught scriptableobject.createinstance.

    Even if I remove all calls and references to FPSMouseLook the error still occurs so it has to be about how I'm making the getcomponent call which is as such;

    Code (csharp):
    1. public class FPSMouseLook : ScriptableObject {
    2.    private CharacterController PlayerCon;
    3.    public void Init() {
    4.          PlayerCon = GameObject.GetComponent<CharacterController>();
    5.    }
    6. }
     
  2. psyydack

    psyydack

    Joined:
    Aug 30, 2013
    Posts:
    93
    Hi!

    You doing it wrong in line 4, change to this :

    Code (CSharp):
    1. PlayerCon = gameObject.GetComponent<CharacterController>();

    GameObject with "G" in uppercase you're doing reference to class, and with G in lower youre doing a reference to instance of that object.
     
  3. Kettlewell

    Kettlewell

    Joined:
    Jun 24, 2015
    Posts:
    19
    Thank you, I didn't realize that but now my code is telling me that gameObject does not exist, I don't have to make an instance of gameObject because I am deriving from ScriptableObject and not monobehaviour do I?
     
  4. psyydack

    psyydack

    Joined:
    Aug 30, 2013
    Posts:
    93
    Maybe you should do, because ScriptableObject ( I think ) don't have an instance of gameObject. But you can turn PlayerCon public and assembly in Editor. Or you can transform your scriptableObject in Monobehaviour.