Last active
May 12, 2023 11:08
-
-
Save cemkoker/1d83dac8386352e9444cbe78f09945cc to your computer and use it in GitHub Desktop.
Unity script to place player in center of the screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Focuses on player in Scene view (a game Object with Tag "Player" is mandatory) by pressing "G" key | |
// Pressing Command-G, places the placer in the center of the scene (by raycasting forward) | |
using UnityEngine; | |
using UnityEditor; | |
[InitializeOnLoad] | |
public class SceneTools | |
{ | |
static Transform playerTransform; | |
static SceneTools() | |
{ | |
SceneView.onSceneGUIDelegate += OnSceneGUI; | |
} | |
private static void OnSceneGUI(SceneView sceneView) | |
{ | |
var e = Event.current; | |
if (e.type != EventType.KeyDown || e.keyCode != KeyCode.G) return; | |
if (e.command) | |
{ | |
// Move the player to the center point of the Scene view | |
var center = sceneView.camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f)); | |
if (Physics.Raycast(center, sceneView.camera.transform.forward, out var hit)) | |
{ | |
if (playerTransform == null) | |
{ | |
playerTransform = GameObject.FindWithTag("Player").transform; | |
if (playerTransform == null) | |
{ | |
Debug.LogWarning("Could not find player object with tag 'Player'"); | |
return; | |
} | |
} | |
playerTransform.position = hit.point; | |
} | |
e.Use(); | |
} | |
// Find the player object in the scene | |
if (playerTransform == null) | |
{ | |
playerTransform = GameObject.FindWithTag("Player").transform; | |
if (playerTransform == null) | |
{ | |
Debug.LogWarning("Could not find player object with tag 'Player'"); | |
return; | |
} | |
} | |
// Focus the scene view camera on the player | |
sceneView.LookAt(playerTransform.position); | |
e.Use(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment