Realtime Cubemap for Reflections
February 25, 2012
A nice script for creating a real time cubemap from an object position for use with a reflection shader to create realtime reflections in Unity. Converted from the JavaScript example. Note: This script requires the Unity Pro license.
using UnityEngine; using System.Collections; public class RealtimeCubemap : MonoBehaviour { public int cubemapSize = 128; public bool oneFacePerFrame = false; private Camera cam; private RenderTexture rtex; private GameObject go; [ExecuteInEditMode] void Start() { // render all six faces at startup UpdateCubemap(63); } void LateUpdate() { if (oneFacePerFrame) { int faceToRender = Time.frameCount % 6; int faceMask = 1 << faceToRender; UpdateCubemap(faceMask); } else { UpdateCubemap(63); // all six faces } } void UpdateCubemap(int faceMask) { if (!cam) { go = new GameObject("CubemapCamera"); go.AddComponent(typeof(Camera)); go.hideFlags = HideFlags.HideAndDontSave; go.transform.position = transform.position; go.transform.rotation = Quaternion.identity; cam = go.camera; cam.farClipPlane = 100; // don't render very far into cubemap cam.enabled = false; } if (!rtex) { rtex = new RenderTexture(cubemapSize, cubemapSize, 16); rtex.isCubemap = true; rtex.hideFlags = HideFlags.HideAndDontSave; renderer.sharedMaterial.SetTexture ("_Cube", rtex); } cam.transform.position = transform.position; cam.RenderToCubemap(rtex, faceMask); } void OnDisable() { DestroyImmediate (cam); DestroyImmediate (rtex); } }
Categorised in: Game development, HowTo
3 Comments
how can i do this?
My friend and I have already got the reflection pretty nice just wondering how can we get around the pro licence thing? poor self taught programming needing assistance urgently please help
I recently saw an extension in the Unity Asset Store that allowed you to render to texture (which you will need for any kind of realtime reflections). Somebody wrote that it was quite slow, which would be logical as it would have to do everything with the cpu.
I can’t remember what it was called and I didn’t find it in the store right now. Maybe I’ll find it later on.