I am doing some physics tests in the editor time, but i met some problems that 2d physics callbacks(OnCollisionEnter2D & OnTriggerEnter2D) are not triggered properly. Here are the main codes.
This is a simple editor window to simulate physics in editor time. Hit the ‘Run Physics’ button to step physics.
public class ScenePhysicsTool : EditorWindow
{
private int times = 1;
private float timestep = 0.01f;
private GameObject obj = null;
private void OnGUI()
{
times = EditorGUILayout.IntField(times);
timestep = EditorGUILayout.FloatField(timestep);
obj = EditorGUILayout.ObjectField(obj, typeof(GameObject), true) as GameObject;
if (GUILayout.Button("Init"))
{
Physics2D.simulationMode = SimulationMode2D.Script;
Physics.autoSimulation = false;
}
if (GUILayout.Button("Run Physics"))
{
StepPhysics();
}
if (GUILayout.Button("Reset"))
{
obj.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
}
}
private void StepPhysics()
{
for (int i = 0; i < times; i++)
{
//2d
Physics2D.Simulate(timestep);
//3d
Physics.Simulate(timestep);
}
}
private void Reset()
{
this.obj.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
this.obj.transform.position = new Vector3(0, 5, 0);
}
[MenuItem("Tools/Scene Physics")]
private static void OpenWindow()
{
GetWindow<ScenePhysicsTool>(false, "Physics", true);
}
}
This is the trigger script that is attached to the gameobjects.
[ExecuteInEditMode]
public class Trigger : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("OnCollisionEnter2D");
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("OnTriggerEnter2D");
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter");
}
private void OnCollisionEnter(Collision collision)
{
Debug.Log("OnCollisionEnter");
}
}
This is the final log result. It’s obvious that only the 3d physics callback is triggered just as I expected.