An object reference is required for the non-static field, method, or property Object.name

Help me please, i found some threads with pretty similar problem, but i still dont get how to solve it.

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

public class HitWall : MonoBehaviour
{
    // Start is called before the first frame update
    GameObject LeftScore;
    GameObject RightScore;
    void Start()
    {
        LeftScore = GameObject.Find("LeftScore");
        RightScore = GameObject.Find("RightScore");
    }

    // Update is called once per frame
    void Update()
    {
       
    }
    void OnCollisionEnter2D(Collision2D col) {
        if ((col.gameObject.name == "Ball") || (GameObject.name == "WallLeft")){
            RightScore.score = RightScore.score + 1;
        }
        else if ((col.gameObject.name == "Ball") || (GameObject.name == "WallRight")){
            LeftScore.score = LeftScore.score + 1;
        }
    }
}

GameObject is a class. This is wrong GameObject.name

It looks like you are trying to detect which gameobject has been hit. You would either want code on each gameobject or as it is a simple 2d game, you could just monitor the x position of the ball.

I think your solution will work, but how can I get name of object that connected with this script(sorry for my English)

this.gameObject.name
1 Like