Camera shake scripts works but camera wont stay in prefab

Hi guys,

So I found a camera shake script that works perfectly for me, kinda.
This script is attached to an explosion that gets instantiated whenever a bomb explodes.
When I add the main camera to the public transform field it does not stay whenever I turn it into a prefab, the field is just empty.

Is there a reason for this or is it a bug?

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour
	// Transform of the camera to shake. Grabs the gameObject's transform
	// if null.
	public Transform camTransform;
	// How long the object should shake for.
	public float shake = 0f;
	// Amplitude of the shake. A larger value shakes the camera harder.
	public float shakeAmount = 0.7f;
	public float decreaseFactor = 1.0f;
	Vector3 originalPos;
	void Awake()
		if (camTransform == null)
			camTransform = GetComponent(typeof(Transform)) as Transform;
	void OnEnable()
		originalPos = camTransform.localPosition;
	void Update()
		if (shake > 0)
			camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount;
			shake -= Time.deltaTime * decreaseFactor;
			shake = 0f;
			camTransform.localPosition = originalPos;

A prefab can’t contain references to objects in a scene. This is because a prefab can be used in any/multiple scenes - therefore references to items in a specific scene would not make sense, because that scene might not be the one that is loaded.

The simplest way to access the camera is to make sure your camera is tagged MainCamera (the initial camera in the scene has this tag by default).

You can then access the main camera via script using Camera.main

So, on line 23, instead of

camTransform = GetComponent(typeof(Transform)) as Transform;

which by the way, is a bizarrely convoluted way of writing: camTransform = transform;

You could have:

camTransform = Camera.main.transform;

Prefab cannot hold reference to gameobject or any of its components class from the scene, because it is not a part of the scene (before instantiating). Your best shot is to find it on the run just after instantiating explosion by either GameObject.Find (slow) or direct access to the object via singleton (fast).

Alternatively you could change your camera into prefab too and see if it works.