Camera shake, everything disappear from screen except canvas.

I made camera shake script and when I use it on button everything except canvas disappear from screen (game is continue to go). I make 2d game and in game view option I set 9:14 (I tried with different views and there is same problem). Here is my code:

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour {

public Camera mainCam;

float shakeAmount = 0.2f;

void Awake() {

    if (mainCam == null) {
        mainCam = Camera.main;
void Update() {

    if (Input.GetKeyDown(KeyCode.T)) {

        Shake(0.1f, 0.1f);
public void Shake (float amt, float length) {

    shakeAmount = amt;
    InvokeRepeating("BeginShake", 0.01f, 0);
    Invoke("StopShake", length);

void BeginShake() {

    if (shakeAmount > 0) {

        Vector3 camPos = mainCam.transform.position;

        float offsetX = Random.value * shakeAmount * 2 - shakeAmount;
        float offsetY = Random.value * shakeAmount * 2 - shakeAmount;
        camPos.x += offsetX;
        camPos.y += offsetY;

        mainCam.transform.position = camPos;

void StopShake()
    mainCam.transform.position =;


I set Camera as empty game object and MainCamera as child. Script is attached on child object.

I have the same problem, can someone tell me if this was resolved?

In the Function StopShake(), try to change the last line of code into
mainCam.transform.localPosition =;
and see what happens. If you change the localPosition into Zero, now the child object will have the same position with the parent object, which should be working.
Hope that helps =))

Here’s a short Youtube video that covers exactly how to code a screen shake effect: How to Code a Screen Shake Effect | Unity Tutorial - YouTube

screen shake