如何在Unity3d C#级别发送一次消息

时间:2017-04-12 18:38:28

标签: c# unity3d

下面是我的脚本,放置在我的播放器子弹上,每次我的玩家开火,玩家子弹生成,并且在击中敌人或拦截器后它会摧毁,在此脚本中我想要在此之后发送损坏消息时,它警告其他敌人,但只有一次在一个级别(每次玩家子弹生成,它不会每次都报警,只有一次),这是我的代码。高级谢谢。

using System.Collections;
public class player_bullet_mover : MonoBehaviour 
{
[HideInInspector]
public Vector3 target;
public GameObject target_object;
public float damage_is;
private player_damage_controller player_damage_script;

// Use this for initialization
void Start () 
{
    player_damage_script = GameObject.FindObjectOfType (typeof(player_damage_controller)) as player_damage_controller;

    if(target == Vector3.zero)
    {
        Destroy(  this.gameObject );
    }
    transform.LookAt (target);
}

// Update is called once per frame
void Update () 
{
    this.transform.position = Vector3.MoveTowards ( this.transform.position , target, 300 * Time.deltaTime );
}

void OnTriggerEnter( Collider other )
{
    if(other.CompareTag("Enemy") )
    {
        other.SendMessage( "damage", 2 );
        Destroy( this.gameObject );
    }
    //call alarm_enemies function here but once in a level, not every time, it generate
}
public void alarm_enemies()
  {
    //send message to enemy script
  }
}

1 个答案:

答案 0 :(得分:2)

我注意到您使用的是Unity的SendMessage功能。不要使用它。您应该使用delegateevent执行此操作。

player_bullet_mover脚本中创建一个事件:

bool sentOnce = false;
public delegate void damaged();
public static event damaged OnDamaged;

player_bullet_mover脚本中,在发生冲突时调用订阅事件的函数。

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Enemy"))
    {
        other.SendMessage("damage", 2);
        Destroy(this.gameObject);
    }

    //call alarm_enemies function here but once in a level, not every time, it generate

    //Send if we have not send this before
    if (!sentOnce)
    {
        sentOnce = true;
        //Alert every enemy
        OnDamaged();
    }
}

从您想要提醒的敌人脚本中,订阅在player_bullet_mover脚本中创建的事件。在OnEnable函数中订阅它,并在OnDisable函数中取消订阅。

void OnEnable()
{
    player_bullet_mover.OnDamaged += damagedCallBack;
}


void OnDisable()
{
    player_bullet_mover.OnDamaged -= damagedCallBack;
}

void damagedCallBack()
{
    UnityEngine.Debug.Log("Damaged!");
}

您可以详细了解here