我们先来看一下OnTriggerStay2D的官方文档。
其大致意思为,对于进入Trigger里的物体,每帧都执行一次检测和逻辑代码。
我们来做一个小Demo。
意图使进入Trigger的物体生命值逐帧递减。
挂载上相应的脚本和组件。
NewBehaviourScript这样写
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private void OnTriggerStay2D(Collider2D collision)
{
collision.GetComponent<healthy>().hp -= Time.deltaTime;
}
}
healthy这样写
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class healthy : MonoBehaviour {
public float hp = 500;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
然而我在运行时发现它减了几秒后就不减了,冷静分析发现是Rigidbody2D休眠造成的。
所以我们要把被检测的一方的Rigidbody2D的睡眠模式改一下。
OK,大功告成。