Note: If you are experiencing your object loading outside of the screen, you may need to adjust the code for the camera you are using. Orthographic and Perspective cameras have a reversed axis when using screenToWorldPoint. Below are two different script variations for each. Make sure to assign your main camera to the place in the inspector.
Source Code for Perspective Cameras
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PSBoundariesPerspective : MonoBehaviour {
public Camera MainCamera; //be sure to assign this in the inspector to your main camera
private Vector2 screenBounds;
private float objectWidth;
private float objectHeight;
// Use this for initialization
void Start(){
screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, MainCamera.transform.position.z));
objectWidth = transform.GetComponent<SpriteRenderer>().bounds.extents.x; //extents = size of width / 2
objectHeight = transform.GetComponent<SpriteRenderer>().bounds.extents.y; //extents = size of height / 2
}
// Update is called once per frame
void LateUpdate(){
Vector3 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x + objectWidth, screenBounds.x * -1 - objectWidth);
viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y + objectHeight, screenBounds.y * -1 - objectHeight);
transform.position = viewPos;
}
}
Source Code for Orthographic Cameras
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PSBoundariesOrthographic : MonoBehaviour {
public Camera MainCamera;
private Vector2 screenBounds;
private float objectWidth;
private float objectHeight;
// Use this for initialization
void Start () {
screenBounds = MainCamera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, MainCamera.transform.position.z));
objectWidth = transform.GetComponent<SpriteRenderer>().bounds.extents.x; //extents = size of width / 2
objectHeight = transform.GetComponent<SpriteRenderer>().bounds.extents.y; //extents = size of height / 2
}
// Update is called once per frame
void LateUpdate(){
Vector3 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x * -1 + objectWidth, screenBounds.x - objectWidth);
viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y * -1 + objectHeight, screenBounds.y - objectHeight);
transform.position = viewPos;
}
}