1

I'm trying to make a pick up weapon system on unity using c#. I'm trying to change a value from a script to another but I'm having some problems. I'm trying to change the weapon number to 1.

using UnityEngine;

public class Pew : MonoBehaviour
{
public int weapon = 0;
}

So, I'm using this line of code

using UnityEngine;

public class PickUpBow : MonoBehaviour
{

    public void OnCollisionEnter2D(Collision2D collision)
    {
    GameObject thePlayer = GameObject.Find("ThePlayer");
    Pew pew = thePlayer.GetComponent<Pew>();
    pew.weapon = 1;
    }
}

But when I touch the object, it gives me the following error: "Object reference not set to an instance of an object Unity", on the following line: Pew pew = thePlayer.GetComponent<Pew>();

Thank you!

Hugo Novais
  • 69
  • 1
  • 7
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – BugFinder Apr 09 '20 at 22:46

2 Answers2

1

I assume the collision is with the player.

The problem is because GameObject.Find("ThePlayer") search the hierarchy for any game object named exactly that way. Maybe there is some blank space in the name. It is not a good practice to use that method because it may cause that kind of problems.

So, instead of:

GameObject thePlayer = GameObject.Find("ThePlayer");
Pew pew = thePlayer.GetComponent<Pew>();

Be better like:

GameObject thePlayer = collision.gameObject;
Pew pew = thePlayer.GetComponent<Pew>();

The problem with this new code is that we assume the collision is with the player, but what if is an enemy?

A good solution is using Tags, and now:

if(collision.gameObject.CompareTag("Player") 
{
    GameObject thePlayer = collision.gameObject;
    Pew pew = thePlayer.GetComponent<Pew>();
}
Marco Elizondo
  • 552
  • 3
  • 9
0

That means thePlayer is null.

This means that the assignment did not work: GameObject thePlayer = GameObject.Find("ThePlayer");

make sure this works: GameObject.Find("ThePlayer");

The docs: https://docs.unity3d.com/ScriptReference/GameObject.Find.html

This function only returns active GameObjects. If no GameObject with name can be found, null is returned.

Make sure the names match correctly!

sommmen
  • 6,570
  • 2
  • 30
  • 51