Trouble with HealthAsPercentage

Hi Folk,
I’ve got a trouble with the HealthBar system.

I’ve followed the video from Ben, however, i’m not able to take off the error with the healthAsPercentage

I’ve try different thing but nothing seems work for now… :frowning:

|Error|CS1061|‘GameObject’ does not contain a definition for ‘healthAsPercentage’ and no extension method ‘healthAsPercentage’ accepting a first argument of type ‘GameObject’ could be found (are you missing a using directive or an assembly reference?)|Crystal Shard RPG|E:\Unity Project\Crystal Shard RPG\Assets\Camera & UI\PlayerHealthBar.cs|23|Active|

this is my Player Script:

[SerializeField] float maxHealthPoints = 100f;

float currentHealthPoint=100f;

public float healthAsPercentage
{
    get
    {
        return currentHealthPoint / maxHealthPoints;
    }
    
}

Hi Vazan,

Is that the whole script?

it’s the only modified, the other one is the imported script from Ben’s asset package for the tutorial.:

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

[RequireComponent(typeof(RawImage))]
public class PlayerHealthBar : MonoBehaviour
{

    RawImage healthBarRawImage;
    GameObject player;

    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        healthBarRawImage = GetComponent<RawImage>();
    }

    // Update is called once per frame
    void Update()
    {
        float xValue = -(player.healthAsPercentage / 2f) - 0.5f;
        healthBarRawImage.uvRect = new Rect(xValue, 0f, 0.5f, 1f);
    }
}

I think your issue here is in your Start method. You are using GameObject.FindGameObjectWithTag, if we look at the documentation for that method we can see that this returns a GameObject, it doesn’t return a Player object, which is what would have the member property healthAsPercentage.

Looking at a code example I have at this end, the code is slightly different.

The player variable is of Type Player;

Player player;

and is initialised in the Start method with this;

player = FindObjectOfType<Player>();

Now it could be that this is from a later lecture, but the issue is pretty much the same, you have a casting issue. Note, find by type should also be safer than by tag as it will be less prone to typos or not being applied.

Also, it may just be because you are using a different version of Unity and there have been some API changes, but I can only see (I didn’t spend a lot of time searching) GameObject.FindWithTag and GameObject.FindGameObjectsWithTag (note the plural), whereas you are calling FindGameObjectWithTag.

I’m guessing you are on lecture 29? Assuming so, if you look under Resources and click on the Lecture Project Changes link it will open a browser tab with the GitHub repository for that specific section and you can see the code Ben uses at this stage;


See also;

Privacy & Terms