Having a bit of trouple with referencing a public variable in one script from another script

So I have the following code:

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

public class JumpPowerup : MonoBehaviour
    public GameObject pickupEffect;
    public MovePlayer movePlayer;

    void OnTriggerEnter(Collider other) {
        if (other.CompareTag("Player")) { //then the player is in contact with the powerup

    private void Pickup(Collider player) {

        //do an effect
        Instantiate(pickupEffect, transform.position, transform.rotation);

        //give the player more jump height by modifying the jumpForce public variable in the MovePlayer script that sits on the Player GameObject

        player.GetComponent<MovePlayer>().jumpForce = new Vector3(0, 20, 0); // this does not work

        movePlayer.jumpForce = new Vector3(0, 20, 0); //this does work: why?

        //gets rid of the powerup

Why does player.GetComponent().jumpForce = new Vector3(0, 20, 0); not work (it gives the error "NullReferenceException: Object reference not set to an instance of an object") while the line below it does and is successfully able to change jumpForce? It is my (clearly incorrect) understanding that these two lines of code would do the same thing.


player.GetComponent() will return null if the object you collided with does not have a MovePlayer component. Are you 100% sure the object you collided with has that component? Try logging some info:

MovePlayer movePlayerFromCollider = player.GetComponent<MovePlayer>();

Debug.Log($"The name of the object we collided with is {player.gameObject.name}. That object has a MovePlayer component: {movePlayerFromCollider != null}");

If that prints false, there is no MovePlayer component on the GameObject you collided with.

Aha! I know the problem now. My character is a snowman, and it is made up of 3 different objects each with there own colliders (head, middle, and bottom). The player GameObject was an empty game object that I created to hold these three things and also govern the movement and physics for the player (it has a rigid body component and the movePlayer script). So, the power up is colliding with one of these parts of the player, which does not have the script on it as the script sits the whole thing, not on any one of the individual components.

Anyway around this? Is there a way to acess the parent of the object that is colliding?

You could use GetComponentInParent<MovePlayer>()