问题
I have 2 identical GameObjects (crates - prefabs) and 2 spots where that crates need to get. When player push first crate to spot 1, OnTriggerStay in script attached to that crate activate and do the job all time (print in console). Problem is that when second crate get to second spot, it do job 20-30 times (print) and then stop, then I need to just touch it (move a little) and again it does job 20-30 times and stop.
Here is script attached to crates:
public class Block : MonoBehaviour
{
public BlockType blockType;
public int blockId;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
private void OnTriggerStay2D(Collider2D col)
{
if (gameObject.GetComponent<Block>() != null)
{
if (col.GetComponent<Block>().blockType == BlockType.Crate && gameObject.GetComponent<Block>().blockType == BlockType.Point)
{
float distance = Vector3.Distance(this.transform.position, col.transform.position);
Debug.Log(col.GetComponent<Block>().blockId + ": " + distance); //for testing, distance is <= 0.05 and it doesn't display
if (distance <= 0.05)
{
PlayScene.CrateOnPoint(col.GetComponent<Block>().blockId);
Debug.Log("On place: " + col.GetComponent<Block>().blockId);
}
}
}
}
}
回答1:
OnTriggerStay is used to detect when a GameObject is still touching with another GameObject once. You should not use it as a way to detect if GameObjects are touching every frame because sometimes, it is only called few times.
The best way to do this is with the Update, OnTriggerEnterXXX and the OnTriggerExitXXX functions with a boolean variable. You set it to true when in the OnTriggerEnterXXX is called then to false when OnTriggerExitXXX is called. You then check this boolean variable every frame in the Update function.
bool triggered = false;
private void Update()
{
if (triggered)
{
//Do something!
}
}
void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Entered");
if (collision.gameObject.CompareTag("SomeObject"))
{
triggered = true;
}
}
void OnTriggerExit2D(Collider2D collision)
{
Debug.Log("Exited");
if (collision.gameObject.CompareTag("SomeObject"))
{
triggered = false;
}
}
来源:https://stackoverflow.com/questions/45940543/ontriggerstay-not-called-every-frame