Create a world with the Physics Core 2D API
Create a new world to add 2D physics objects to, or fetch the default world Unity automatically creates.
Read time 2 minutesLast updated 12 days ago
To create physics objects using the Physics Core 2D API, you first need to create a physics world.
Prerequisites
Before you create a physics world, follow these steps:
- Create a MonoBehaviour script file: from the main menu, select Assets > Create > C# Script.
- To import the API namespace, add
Unity.U2D.Physicsat the top of the script.using Unity.U2D.Physics;
Fetch the default world
Unity automatically creates a default world. To fetch it, follow these steps:
-
Get theproperty from the
defaultWorldclass.PhysicsWorldPhysicsWorld world = PhysicsWorld.defaultWorld; -
Attach the script to a GameObject in your scene.
-
Enter Play mode to run the script.
To adjust the properties of the world, refer to Configure global Physics Core 2D API settings.
Unity creates or recreates the default world at the following times:
- When the Editor starts.
- When you enter or exit Play mode.
- When your built application starts.
Create your own world
To create your own world, follow these steps:
-
Create a publicobject that holds the world properties and displays them in the Inspector window. For example:
PhysicsWorldDefinitionpublic PhysicsWorldDefinition worldDefinition = new PhysicsWorldDefinition();A new definition has a set of default values. For example, gravity is set to -9.81f. For more information about definitions and changing the default values, refer to Configure objects using definitions.You can also useto get a definition object with the default values.PhysicsWorld.defaultDefinition -
Create aobject with the definition. For example:
PhysicsWorldPhysicsWorld world = PhysicsWorld.Create(worldDefinition); -
Attach the script to a GameObject in your scene.
-
To adjust the properties of the world, modify the values in the Inspector window.To configure the world in your script instead, set the properties of the definition object before you create the world. For more information, refer to Configure objects using definitions.
-
Enter Play mode to run the script and create the world.
Pause a world
A world starts running as soon as you create it. To pause the simulation, set the property of the world object to .
pausedtrueExample
The following example fetches the default world and logs the gravity value to the Console window.
using UnityEngine;using Unity.U2D.Physics;public class GetDefaultWorld : MonoBehaviour{ void Awake() { // Fetch the default physics world PhysicsWorld world = PhysicsWorld.defaultWorld; // Log the gravity value to check the world is created Debug.Log("The gravity in this world is " + world.gravity); } }