- Home /
Creating & accessing a function from a diffrent "OnTriggerEnter" Function
Hey guys, so i am having allot of trouble with this.
I had a function on my "player" that whenever it collided with a enemy, health would be taken off, it worked fine untill my player remained still and the enemys ran into him, in which nothing would happen. Thanks to you guys someone pointed out that it was because the "enemy" was colliding with the "player", not the other way around.
so the solution would be to create a function on the "enemy" that activated the function on my main script (attached to my player) so that the important code can be executed and my character can loose health.
does anyone know the basics? i have looked up heaps of answers about this but i unfortunately still cant get it to work.
does anyone know the code to access another function in another code and thence forth activating that function? how would i write the function in the "main code" after i have successfully gotten my "enemy code" to access it?
Dave...
Answer by ExTheSea · Apr 29, 2013 at 04:20 PM
Hey Dave. So we meet again :)
What you could do is something like this:
In the Enemy-Script:
function OnTriggerEnter(collision : Collider){
if(collision.gameObject.tag == ("Player")){
collision.gameobject.SendMessage("CauseDamage");
}
}
The method SendMessage calls a function in the script of another object. Here is a link to the script reference: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html
and in the Player-Script you posted in the other question you add this:
function CauseDamage(){
BurgersGui.Burgers +=BurgerNegative;
transform.localScale += Vector3(-0.1,-0.1,-0.1);
}
I hope this works for you and if not just ask.
hahahaha, we do meet again, you have helped me so much, thankyou. ok so i will give your code a try. thankyou so much, legend.
haha, we do meet again, thankyou for all your help. so i tried it but i get an error on the following line "collision.gameobject.Send$$anonymous$$essage("CauseDamage");"
the error says "Object Reference not set to an instance of an object"
i figured it out, i had to use this if(collision.gameObject.tag == ("Player")){ gameObject.Find("Player").Send$$anonymous$$essage("Damage");
you were still right though
Im not sure what to do here though, the script works fast and causes dammage way to fast, how can i make my character invincible a few seconds the damage?
private var nextDamageTime = 0.0;
var DamageRate = 0.05;
function CauseDamage(){
if (Time.time - DamageRate > nextDamageTime)
nextDamageTime = Time.time - Time.deltaTime;
while( nextDamageTime < Time.time) {
//Do your damage stuff
nextDamageTime +=DamageRate;
}
}
This is a part of my FPS Gun-Script but it should work in your case (maybe you can even replayce the while with an if).
Let me know if it works.