The variable player of HealthItem has not been assigned. but it has been

I’ve been trying to get a health item to work as a button in my inventory. I’ve tried assigning the player in code and by changing the variable to public but it isn’t detecting it. Why? When I change it to public and drag and drop the Player object into the public slot, it tells me “UnassignedReferenceException: The variable player of HealthItem has not been assigned. You probably need to assign the player variable of the HealthItem script in the inspector.” But as you can see in the screenshot, I have.
I don’t understand what is going on.
I’ve tried restarting unity and saving the scene/project but nothing is working.

Code

public class HealthItem : MonoBehaviour
{
    public GameObject effect;
    public float healFactor;
    private Transform pos;
    public GameObject player;
    // Start is called before the first frame update
    private void Start()
    {
       // player = GameObject.FindGameObjectWithTag("Player");
        pos = player.transform;
    }

    public void Use()
    {
        if (player.GetComponent<PlayerScript>().health < 4)
        {
            Debug.Log("Used");
            Instantiate(effect, pos.position, Quaternion.identity);
            player.GetComponent<PlayerScript>().health += healFactor;
            Destroy(gameObject);
        }
    }
}

Unity also won’t let me tag this with anything >.>

I assume you have another GameObject with “HealthItem” script attached and there is no Player assigned to the player variable.
Check all GameObjects where this script might be attached,

2 Likes

EDIT: I’m seeing the player slot in the button prefab (Caused the exception, so you were indeed correct)…When I delete the ‘HealthItem’ script from the button prefab but leave it on the item itsself, it doesn’t do anything. >.> ugh being new sucks hardcore

Nope, Very sadly I don’t. I wish it would be that easy, but I went through all my objects and that health item is the only one with that script attached :frowning: I’ve been learning unity for four days now. I’m loving it but I’m running into this specific problem more often than I care to admit but this is the only time that I seem to have done nothing wrong… Thank you for replying so quick by the way.

double click on this red error message and say which line in the script makes the error
start the game, switch to the scene tab and check if player is still assigned

1 Like

“EDIT” changes in posts goes to the end of posts usually, as it’s confusing to read otherwise.

Glad I was able to help :slight_smile:

We all were starters one day, feel free to keep asking what you are not able to find googling fast :wink:

How you trigger “Use()” ?
Do you update your healthbar and other stuff after “Use()” ?

EDIT:
And another hint, you may use

public PlayerScript player;

instead of the GameObject. You would save yourself .GetComponent() on each call.
Unity is very good in performing directly assign components over grabbing through GetComponent on runtime (it’s not toooo poor, but you know, whatever consumes CPU…^^)

2 Likes

Sorry about that lol I’ll change it

The whole process goes like this… I’ve got an Item prefab with a “Pickup Item” script that takes an “Item button” as a public gameobject. In the Health button I’ve got an “onClick” event that calls the use method of the health item script. and if the user clicks the little X then a “SpawnDroppedItem” method is called which is supposed to destroy the child UI image of the slot and ‘drops’ the item back into the world

New problem (I don’t understand how I’m messing this up so bad, I had it working well on a different game LOL GRRRR) I’m now getting the same error but in my “SpawnItem” script where I get the players position (line 15)
I absolutely suck at this right now lol
Code

public class SpawnItem : MonoBehaviour
{
    public GameObject item; // Child of parented slot
    private GameObject player;
    private bool facing;
    Vector2 pos;

    private void Start(){
        player = GameObject.FindGameObjectWithTag("Player");
        Debug.Log("Player: "+ player);
        pos = player.transform.position;
    }

    public void SpawnDroppedItem(){
        Debug.Log(item);
        facing = player.GetComponent<PlayerScript>().facingRight;
        if (facing == true){
            Vector2 playerPos = new Vector2(pos.x +3, pos.y);
            Instantiate(item, playerPos, Quaternion.identity);
        }
        if (facing == false){
            Vector2 playerPos = new Vector2(pos.x -3, pos.y);
            Instantiate(item, playerPos, Quaternion.identity);
        }

    }
}

Here is what the debug says… "
Player:
UnityEngine.Debug:Log(Object)
"
EDIT: I’M A MORON OOOOOOOOOOOOOOF Biggest oof ever. I forgot that I change the players tag when they’re on the floor/when jumping. Which means it never finds the player…OH MY GOODNESS. Time to see if setting ‘player’ to public and dragging it to the slot will work…
EDIT2: That was it…I’m so ashamed lmao THAT SUCKED SO HARD >.< uuuuggggh all that stress and frustration because I FORGOT THAT I’M NOT USING A Player TAG RENSAIVOFDNVFDLKSNCEWOSANCIRKS <<< That’s yelling lmao
THANK YOU SO MUCH FOR YOUR HELP. I’m used to stackoverflow where everyone seems to hate you when you’re new and don’t know everything. Even made a new account so I didn’t have to worry about getting down voted all the time when asking a question that might be simple for them but complex for me…again, being new sucks. Thank you for being so nice!

2 Likes

don’t punish yourself :hushed:

The people here can’t be an old, big and wise rabbit because the Unity makes something new every day and most of us are still learning it. And you have founded the error :wink:

1 Like

5141537--508994--Screenshot (4).png 5141537--508997--Screenshot (3).png [quote=“vakabaka, post:7, topic: 764405, username:vakabaka”]
don’t punish yourself :hushed:

The people here can’t be an old, big and wise rabbit because the Unity makes something new every day and most of us are still learning it. And you have founded the error :wink:
[/quote]
Thank you :slight_smile: I appreciate the compassion. I’ve got another problem now lol. My button isn’t instantiating in the slot it’s getting assigned to, which doesn’t make sense because it has the same scripts as the other, they’re just on a different ite. The original health item button spawns perfectly in the slot so I’m confused lol.

Here’s the script LOL

public class PickupItem : MonoBehaviour
{
    private Inventory inventory;
    public GameObject itemButton;

    private void Start(){
        inventory = GameObject.Find("Player").GetComponent<Inventory>();
    }

    void OnTriggerEnter2D(Collider2D other){
        if (other.gameObject.name == "Player"){
            for (int i = 0; i < inventory.slots.Length; i++){
                if (inventory.isFull[i] == false){
                    //Item can be added to inventory
                    inventory.isFull[i] = true;
                    Instantiate(itemButton, inventory.slots[i].transform, false);
                    Destroy(this.gameObject);
                    break;
                }
            }
          }
        }
    }

I don’t understand how it could work perfectly fine for the other food item (healing item) but not for this one. What kind of witchcraftery is this?! I ask my computer. lol.
The position of the other button ( not the original button ) consistently shows in the same spot every time, even when it is the only thing that’s picked up.
Again, I really appreciate the help, I’m used to having to teach myself everything from Documentation and tutorials and never having any help which makes having help (for a change) EXTREMELY encouraging. I’ve never felt so much fun while developing something. I’ve been teaching myself python for a year now and I’ve made some fun programs, started game developing (mainly) to learn C# but now I’m in love with developing games.

EDIT: I tried resetting the transform in the prefab but that didn’t work :eyes:

has this meat prefab zero in the x and y position ?

I have never used Instantiate in the parent.
Just for test you can try:

Instantiate(itemButton, inventory.slots[i].transform.position, transform.rotation);

What do you mean you never used instantiate in the parent?
When I use what you provided it disappears lol but for some reason when I just started up Unity, it gave me the “Cannot implicitly convert Transform to Vector3” exception but when I used the second argument of what you gave, the exception went away.

Day just went bad so I’m done for the day anyway, Thank you for the replies :slight_smile:

I mean, there are different ways how to use Instantiate, you can overload it:
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

as all the time, pause the game, switch into the scene and check where the object is (in most case it is behind the camera or its order in layer is too low.

1 Like

I’ll check that out. Thank you again!!! You two have no idea how much I appreciate you, seriously.

@vakabaka I figured it out, I forgot to reset the HealthButton prefab attached to the other health item! :smile: Yay!!!
Thank you again for you suggestions :smile:

2 Likes