ScreenShake in Unity Canvas (Alternative Approach)

I recently developed a casual game Hit Ah Fish and wanted to perform a camera shake. In this particular project, All of my GameObjects operate within a canvas. So of course my first instinct was simply to google ‘Camera Shake Unity Canvas’ which lead me to a Yunolab blog post. This post tweaks the strategy applied in that post. Yuno achieved the screen shake effect by changing the renderMode of the canvas to World Space at the beginning, performing the screen shake on the camera and then reverting the canvas back to its original state at end.

This approach is fine but in my case, changing the canvas renderMode simply gives a blank display on my camera view. Now I’m sure if there is a simple solution to adapt Yuno’s approach to my project but I was already pretty far into development and didn’t want to mess around too much.

So, instead of shaking the camera, I decided to instead simply shake the background! The script below shows how this can be achieved

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenShaker : MonoBehaviour {

    public float shakeAmount = 10f;

    private float shakeTime = 0.0f;
    private Vector3 initialPosition;
    private bool isScreenShaking = false;

    //Code adapted from Camera Vibration in Canvas Based Unity Game · Yuno's Wonderland

    // Use this for initialization
    void Start () {
	// Update is called once per frame
	void Update () {
		if(shakeTime > 0)
            this.transform.position = Random.insideUnitSphere * shakeAmount + initialPosition;
            shakeTime -= Time.deltaTime;
        else if(isScreenShaking)
            isScreenShaking = false;
            shakeTime = 0.0f;
            this.transform.position = initialPosition;


    public void ScreenShakeForTime(float time)
        initialPosition = this.transform.position;
        shakeTime = time;
        isScreenShaking = true;

Most of the script has already explained by Yuno’s blog post. To implement, you’d simply attach this script to your background image and call ScreenShakeForTime whenever you need screen shake event. This method also keeps your other canvas objects stable which is a nice effect in itself depending on your use case. If you desire additional objects to shake along with the background, you can add this script to all those other GameObjects and call as desired.

An alternative that’s easy to code and implement. That’s all for this one folks.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.