- Home /
Question by
iRaaptor · Aug 07, 2014 at 09:53 AM ·
getcomponentclassmethod
Accessing a method / void from another class?
using UnityEngine;
using System.Collections;
public class bullet : MonoBehaviour {
private Ray2D bulletRay;
private Vector2 rayOrigin;
private Vector2 rayDirection;
private RaycastHit2D bulletRayHit;
public enemy[] enemyAI;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
rayOrigin = (Vector2)transform.position;
rayDirection = transform.up;
bulletRay = new Ray2D(rayOrigin,rayDirection);
bulletRayHit = Physics2D.Raycast(rayOrigin,rayDirection);
Debug.DrawRay (rayOrigin, rayDirection);
enemyAI = gameObject.GetComponents<enemy>();
}
void OnTriggerEnter2D (Collider2D col)
{
if(col.gameObject.name == "prop_Cube")
{
Destroy(gameObject);
}
if(col.gameObject.name == "enemy")
{
Destroy(gameObject);
enemyAI = col.transform.parent.GetComponents<enemy>();
enemyAI[0].bleed();
}
}
}
I want bleed to be activated when the bullet collides with the enemy.
Comment
It looks like you're on the right track with GetComponent (which is one of the most useful calls in Unity).
Are you having any particular problem with this approach? You didn't say what's giving you trouble.
you can access any method of class in other class but you need to create instance of that class and method must be public.
if(col.gameObject.name == "enemy")
{
Destroy(gameObject);
enemyAI = col.transform.parent.GetComponents<enemy>();
enemyAI[0].bleed();
}
If you destroy the enemy before you call that it will never be called.I sugest you try it like this:
if(col.gameObject.name == "enemy")
{
StartCoroutine(Bleed());
}
IEnumerator Bleed()
{
enemyAI =col.transform.parent.GetComponents<enemy>();
enemyAI[0].bleed();
yield return new WaitForSeconds(1);
Destroy(this.gameObject);
}
Your answer
