GuiTexture Width Change

Hallo i am bigginer at js and i made a js so i can use my damage scripts to reduse the Width of my GuiTexture as i have made it a healthbar. Here is my script but i dont know what’s wrong :

var HP : int = 100;

function Start () {
    HP = guiTexture.texture.width;
}
function Update () {
    transform.width (HP);
}

I would also want to make my player change location to 0.0.0 if HP or width is <= 0

That’s totally wrong: you must get the GUITexture initial width from guiTexture.pixelInset.width and save it, then multiply by HP/100 and set it back at Update. But this script should be attached to the GUITexture object, which cannot be childed to the player! . Since the health bar can’t be a child of the player, modifying the HP variable and respawn the player will be a bit tricky. A better alternative is to attach the health script to the player and use a reference to the GUITexture instead of the property guiTexture, like this:

  • Player health script:
// drag the GUITexture from the Hierarchy view to this field in the Inspector:
var healthBar: GUITexture;
var HP : int = 100;
var lives: int = 3; // lives available
var respawnPoint = Vector3.zero; // respawn position

private var width100: float; // the initial healthBar width

function Start () {
    width100 = healthBar.pixelInset.width;
}

function Update () {
    // set the health bar width:
    healthBar.pixelInset.width = width100 * HP / 100;
    if (HP <= 0){ // player has died?
        if (lives > 0){ // if there are more lives...
            lives--; // decrement lives...
            HP = 100; // restore HP...
            transform.position = respawnPoint; // move to respawn point
        } else {
            // sorry, no more lives - game over!
            Application.Quit();
        }
    }
}

// function that applies the damage:
function ApplyDamage(damage: float){
    HP -= damage;
}

In the other script, you can apply damage in the collision event like this:

function OnCollisionEnter(col: Collision){
  col.transform.SendMessage("ApplyDamage", 5, SendMessageOptions.DontRequireReceiver);
}