Archives

Realtime Cubemap for Reflections

February 25, 2012 by

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);
    }
}

String formatting

February 2, 2012 by

Something small but usefull is the String.Format function, with which you can format your numerical outputs:

using System;
using System.Collections;

...

// formatted float with three zero padded digits
// in front of the "." and three digits after it.
debugText += String.Format("H{0:000.000}\n", heading);

// formatted int with formats for positive;negative;zero values
debugText += String.Format("S{0:+000;-000; 000}\n", speed);