Need to Access Variables from Other Scripts

I need help figuring out how to change a variable from another object.
I have one object named Player that has a public float named “size”, and I have a second object named Circle that I want to be able to increase size from, but I can’t. This is my code in Circle:

 void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.name == "Player")
        {
            this.GetComponent<playerMovement>().size += 1;
        }
    }

Whenever I run this code I get a nullreferenceexception error. I am very new to Unity and C#, so please explain it to me like I have no idea what code even is.

I believe your best bet would be to start here,

Beginner Scripting - Unity Learn

Follow the tutorials, they are very helpful to beginners. Do not skip any and take your time to understand what each lesson is trying to teach you.

1 Like

@jbnlwilliams1 's advice is spot-on. However, for this particular case, the problem is that you’ve determined the other object (coll.gameObject) is the player, but instead of trying to get the playerMovement component on that object, you’re trying to get it on this one (i.e. the object that this code is attached to.

Changing this.GetComponent to coll.gameObject.GetComponent will probably fix it.

But you’re not going to get very far running into this sort of thing all the time and having no idea what’s going on, so it’s definitely worth putting your own project aside for a while and spending a month or two going through the tutorials.

Thank you, I’ll look at the tutorials.