How to use a function from another script
using UnityEngine;
using System.Collections;
public class Obstacle : MonoBehaviour {
void OnCollisionEnter2D(Collider2D coll){
}
}
How do I call a function from the "Death" Script if a obstacle using this script hits the player? And please explain the steps if you can. Thank you.
using UnityEngine;
using System.Collections;
public class Death : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
Answer by Namey5 · Oct 03, 2016 at 06:09 AM
void OnCollisionEnter2D (Collider2D col)
{
if (col.GetComponent<Death>()) //If the object has the death script, execute the function
col.GetComponent<Death>().StartDeath (); //Call the 'StartDeath' function from the 'Death' script
}
And then in your 'Death' class, you would simply have something like the following;
void StartDeath ()
{
//Do stuff
}
Don't forget to have collider on both object and player.
If you were trying to find function that didn't use colliders, you'd be making references to game object or script. https://unity3d.com/learn/tutorials/topics/scripting/getcomponent
For game manager scripts/objects you should look into singleton setups.
Your answer
Follow this Question
Related Questions
How can I detect the color that the ball has collided with? 3 Answers
Advance Colision Detection 1 Answer
How can I change 'Order in Layer' 1 Answer
why the jump doesn't works? 1 Answer