Here's how to create an instance of an object at the mouse position when the player clicks anywhere in the room using GameMaker Studio 2 (GML).
Open your object's Event Editor. Add a Mouse > Left Pressed event (or Right Pressed for right-click).
// Ensure click is within room boundaries
if (mouse_x >= 0 && mouse_x <= room_width && mouse_y >= 0 && mouse_y <= room_height) {
// Create instance at mouse coordinates on the "Instances" layer
instance_create_layer(mouse_x, mouse_y, "Instances", obj_YourObject);
}
mouse_x, mouse_y: Built-in variables for current cursor position.room_width, room_height: Current room dimensions. The if check prevents errors if the mouse is technically outside the room view.instance_create_layer(x, y, layer, object): Spawns the object. Replace obj_YourObject with your actual object name. Ensure the layer name ("Instances") matches your room setup.Use a variable flag to allow only one creation:
// Create Event: Initialize flag
can_spawn = true;
// Left Pressed Event
if (can_spawn) {
if (mouse_x >= 0 && mouse_x <= room_width && mouse_y >= 0 && mouse_y <= room_height) {
instance_create_layer(mouse_x, mouse_y, "Instances", obj_YourObject);
can_spawn = false; // Disable further spawns
}
}
instance_number(obj_YourObject) < max_limit before spawning.