- Home /
How to send messages
So I have game and it workds except when I get hit, I don't know how to decrease energy. In the GUIText object I have this code:
#pragma strict
var health : Number = 30;
function Start () {}
function Update () {
GetComponent(GUIText).text = health + "/30";
}
function DecreaseHealth()
{
health--;
}
but I dont know how to call it inside this code(the next bit of code resides in my enemies.):
#pragma strict
function Start () {
}
function Update () {
}
function OnCollisionEnter(victim : Collision)
{
if(victim.name == "First Person Controller")
{
//Code to decrease energy and sends a message to the GUIText object
}
}
So could I send a message from inside the second block of code into the first to call the method DecreaseEnergy? If yes then how?
Sorry Qato messes up your code so bad. Tried to fix it. Can you edit?
Answer by GC1983 · Aug 15, 2012 at 09:49 PM
First, take the GetComponent call out of Update(). You GetComponent only needs to be called once. Put it in Awake() or Start().
You can go about this two ways. Have a OnTriggerEnter()call on your player object and if any other tagged objects make collision with the player character, then decrease the health.
Or you could put the OnTriggerEnter()call the enemy objects and if they each hit the player object, execute health.
I would recommend putting the OnTriggerEnter() on the player object. So in the player script do this
#pragma strict
public var health : int = 30;
var PlayerHealthDisplay : guiText;
function Update()
{
PlayerHealthDisplay.text = "" + health;
}
function DecreaseHealth()
{
health--;
}
function OnTrigger(victim : Collision)
{
if(victim.gameObject.tag == "enemy")
DecreaseHealth();
}
Hope this helps.
This may not be entirely correct, but it should give you a good start.
Answer by DaveA · Aug 15, 2012 at 09:35 PM
If both scripts are on the same object then just call SendMessage("DecreaseHealth"); If it's on a different object, get that object and call thatObject.SendMessage("DecreaseHealth");
I get an error that is saying I need a non-static member of UnityEngine.Component to access Send$$anonymous$$assage...
Your answer
Follow this Question
Related Questions
How to Send Message to other GameObject 3 Answers
BroadcastMessage 1 Answer
Flame Thrower - Particle Collision Help 1 Answer
Pass Enum To Function Parameter 2 Answers
How do i Specify a Receiver for a Send Message Function? 2 Answers