Hello - My player’s vitality is reduced each time it collides with an object. I would like this to be shown in my health bar, with the bar decreasing accordingly.
Here’s the code I wrote to reduce the vitality (I don’t know if it’s relevant):
var vitality = 100.0;
function OnCollisionEnter(collision:Collision)
{
if( collision.gameObject.tag == "Player" )
{
vitality = vitality - 10.0;
Debug.Log(vitality);
}
}
But I just can’t work out how to use this vitality value in order to affect the health bar. Here’s the script I attempted:
var scriptPlayerHealth : testHealthtwo; //name of script
function Start () {
}
function Update () {
healthBar.playerEnergy = GameObject.Find("vitality");
}
Perhaps the gameObject.Find is completely the wrong method, as this is a float rather than integer?
So I was hoping that someone could give me a pointer in the right direction? (Sorry, I am looking around the forums and scripting reference, I’m just finding it difficult to understand)
Thanks, Laurien
1 Answer
1
Hmm this code example seems a bit problematic to me. I would use gameObject.name instead of tag for the player since you only have one player right?
To make things easier you could have the collision even occur on the player object. In which case you would not have the line:
if( collision.gameObject.tag == “Player” ) {
it would be something more like
if (collision.gameObject.name == “damageObject”)
{
vitality += -10;
}
If you want to do this from another script you could make the vitality be a static variable.
public static float vitality;
Then to access the vitality variable of the player from the collider objects script go:
{ if( collision.gameObject.tag == “Player” ) {
//assuming player script is called PlayerScript
PlayerScript.vitality += -10;
Debug.Log(vitality);
}
Hopefully that helps you a bit but these answers are posted all over these forums I believe so I’ll just leave this limited information. You can solve this problem with a bit of research on the forums or documentation. Sounds like you just need to learn the syntax a bit more.
Also you may want to consider using a trigger for this kind of behavior rather than a collision.
Here’s one example:
void OnTriggerEnter(Collider triggerObject)
{
if (triggerObject.gameObject.name == "Player")
{
PlayerScript.vitality += -10;
}
}
}
Read this page : http://answers.unity3d.com/page/newuser.html For any help, please format your code. You can do this by highlighting all your code, then clicking the 10101 button at the top of the edit window. Watch : http://video.unity3d.com/video/7720450/tutorials-using-unity-answers
– AlucardJayThanks for the link - I've given it a good read :)
– laurienash