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!

1

2 Answers 2

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>();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much dude, I was trying to fix this for 2 hours, you're the best. It worked perfectly
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!

1 Comment

If I'm trying to change a intager, how do I assign a GameObject?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.