GetComponent returns null

Hi all,

I am receiving null when I perform a GetComponent(). I saw that this problem is quite frequently asked on this forum, in these cases the problem is mostly caused by:

  • The script not being attached to the gameobject
  • The instance variable not being initialized

I don’t think this is the cause here though - or I am missing something. As following my code (note that I am new to Unity). In the console log I can see the following output:

Start
 PlayerBall is null
 End

Meaning the LineRenderer linked to the gameobject can be resolved, but the Player object can not.

Player class:

public class Cue : MonoBehaviour {
    public GameController game;
    public LineRenderer line;
    public Player playerBall;

    Cue()
    {

    }
	void Start () {
        Debug.Log("Start");
        line = GetComponent<Cue>().line;
        if (line == null)
        {
            Debug.Log("Line is null");
        }
        playerBall = GetComponent<Player>();
        if (playerBall == null)
        {
            Debug.Log("PlayerBall is null");
        }
        Debug.Log("End");
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        /* do stuff */
    }

    void OnMouseDown()
    {
        
    }
}

In Unity, the following properties are set:
59556-capture.png

The Player object:

public class Player : MonoBehaviour
{
    private int count;
    public Text UIScore;
    public Rigidbody rb;

    protected void Start()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;
        updateScore();
    }
    void FixedUpdate()
    {
        /* do stuff*/
    }

    void OnMouseDown()
    {
    /* do stuff */
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ball"))
        {
            count++;
        }
        updateScore();
    }

    void updateScore()
    {
        UIScore.text = "Player ball Collision count: " + count.ToString();
    }
}

you wrote a dirty code. In Cue class you have line object(LineRenderer) so you don’t need to use
“line = GetComponent().line;” and also
“playerBall = GetComponent()”;