Home > Mobile >  cannot access non static method "GetComponent" in static context, despite me not declaring
cannot access non static method "GetComponent" in static context, despite me not declaring

Time:03-07

I am currently working on making a class accessible from other scripts. Below is what I have coded.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    [RequireComponent(typeof(Rigidbody2D))]
    [RequireComponent(typeof(BoxCollider2D))]
    // Start is called before the first frame update
        public class _move
        {

            private float _sizex;
            private float _sizey;
            public _move(float sizx, float sizy....etc)
            {        


                _sizex = sizx;
                _sizey = sizy;
            }

    
            public  void regularmove(float sizex, float sizey...etc)
            {
                GameObject _player;
                _player =  GameObject.GetComponent<GameObject>();
                BoxCollider2D bc2d;
                bc2d = _player.GetComponent <BoxCollider2D>();
                bc2d.offset = new Vector2(locationx   1, locationy);
            }
        }

however, when I try to compile it, it gives me an error.

    cannot access non-static method"GetComponent"

on this line of code

    _player =  GameObject.GetComponent<GameObject>();

I do not know why this is happening because I have not declared the class as static, and do not really know the properties of GetComponent that well. Can someone tell me what is happening and how I can solve this? Also, when I change

    GameObject _player; 
    to
    public GameObject player;

the scripts below suddenly cease to work, giving me errors like

    cannot resolve symbol _player 

what exactly is happening here? Thanks in advance!

CodePudding user response:

The issue is that GetComponent() in the GameObject is not marked as static, but by calling GameObject.GetComponent<GameObject>(); you are trying to access it as a static method.

You need to instantiate a GameObject first, then make the call to GetComponent(), i.e.:

_player = new GameObject().GetComponent<GameObject>();

As a comparison, you can explore what your options are with the DateTime class in the two different contexts.

In a static context, you can call members like Today, UtcNow, MinValue, which don't need a specific DateTime value to be able to calculate their return value.

But to be able to call e.g. DayOfWeek or AddDays(), you need a defined DateTime instance to call them on, because they need some context to base their calculations on.

// Static examples
var today = DateTime.Today;
var utcNow = DateTime.UtcNow;
var minDate = DateTime.MinValue;

// Non-static examples
var dayOfWeek = today.DayOfWeek;
var tomorrow = today.AddDays(1);

var inlineDayOfWeek = new DateTime(2022, 3, 7).DayOfWeek;
  • Related