Skip to content

Instantly share code, notes, and snippets.

@pyrobot
Created December 23, 2012 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pyrobot/4363640 to your computer and use it in GitHub Desktop.
Save pyrobot/4363640 to your computer and use it in GitHub Desktop.
(Unity3D) Attach to a Camera and on runtime, the script creates a background gradient plane and initially fills it with the colors set in the Editor. Other scripts can then change the gradient color by calling: BackgroundPlane.TopLeftColor = new Color(...); // or TopRightColor, BtmLeftColor, BtmRightColor
using UnityEngine;
using System;
using System.Collections;
public class BackgroundPlane : MonoBehaviour {
static BackgroundPlane _this;
public Color topLeftColor, topRightColor, btmRightColor, btmLeftColor;
Mesh thisMesh;
Camera thisCam;
GameObject backgroundPlane;
public static Color TopLeftColor {
get { return _this.topLeftColor; }
set { _this.topLeftColor = value; _this.setMeshColors(); }
}
public static Color TopRightColor {
get { return _this.topRightColor; }
set { _this.topRightColor = value; _this.setMeshColors(); }
}
public static Color BtmLeftColor {
get { return _this.btmLeftColor; }
set { _this.btmLeftColor = value; _this.setMeshColors(); }
}
public Color BtmRightColor {
get { return _this.btmRightColor; }
set { _this.btmRightColor = value; _this.setMeshColors(); }
}
void Awake() {
_this = this;
thisCam = _this.camera;
}
void Start () {
if (thisCam == null) {
throw new MemberAccessException("BackgroundPlane must be attached to a Camera object.");
}
float farClip = thisCam.farClipPlane - 0.01f;
Vector3
topLeftPosition = thisCam.ViewportToWorldPoint(new Vector3(0, 1, farClip)),
topRightPosition = thisCam.ViewportToWorldPoint(new Vector3(1, 1, farClip)),
btmLeftPosition = thisCam.ViewportToWorldPoint(new Vector3(0, 0, farClip)),
btmRightPosition = thisCam.ViewportToWorldPoint(new Vector3(1, 0, farClip));
Vector3[] verts = new Vector3[] {
topLeftPosition, topRightPosition, btmLeftPosition, btmRightPosition
};
int[] tris = new int[] {
0, 1, 2, 2, 1, 3
};
thisMesh = new Mesh();
thisMesh.vertices = verts;
thisMesh.triangles = tris;
backgroundPlane = new GameObject("_backgroundPlane");
backgroundPlane.transform.parent = transform;
backgroundPlane.AddComponent<MeshFilter>().mesh = thisMesh;
backgroundPlane.AddComponent<MeshRenderer>().material = new Material(
"Shader \"BackgroundPlaneShader\" {" +
"SubShader {" +
" Pass {" +
" ColorMaterial AmbientAndDiffuse "+
" }" +
"}" +
"}"
);
setMeshColors();
}
void setMeshColors() {
thisMesh.colors = new Color[] {
topLeftColor, topRightColor, btmLeftColor, btmRightColor
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment