UnityEngine.Shader.Find(string)

Here are the examples of the csharp api UnityEngine.Shader.Find(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

74 Examples 7

19 Source : DownloadTexture.cs
with GNU General Public License v3.0
from aelariane

private IEnumerator Start()
    {
        WWW www = new WWW(this.url);
        yield return www;
        this.mTex = www.texture;
        if (this.mTex != null)
        {
            UITexture ut = base.GetComponent<UITexture>();
            if (ut.material == null)
            {
                this.mMat = new Material(Shader.Find("Unlit/Transparent Colored"));
            }
            else
            {
                this.mMat = new Material(ut.material);
            }
            ut.material = this.mMat;
            this.mMat.mainTexture = this.mTex;
            ut.MakePixelPerfect();
        }
        www.Dispose();
        yield break;
    }

19 Source : UIDrawCall.cs
with GNU General Public License v3.0
from aelariane

private void UpdateMaterials()
    {
        bool flag = this.mClipping != UIDrawCall.Clipping.None;
        if (flag)
        {
            Shader shader = null;
            if (this.mClipping != UIDrawCall.Clipping.None)
            {
                string text = this.mSharedMat.shader.name;
                text = text.Replace(" (AlphaClip)", string.Empty);
                text = text.Replace(" (SoftClip)", string.Empty);
                if (this.mClipping == UIDrawCall.Clipping.HardClip || this.mClipping == UIDrawCall.Clipping.AlphaClip)
                {
                    shader = Shader.Find(text + " (AlphaClip)");
                }
                else if (this.mClipping == UIDrawCall.Clipping.SoftClip)
                {
                    shader = Shader.Find(text + " (SoftClip)");
                }
                if (shader == null)
                {
                    this.mClipping = UIDrawCall.Clipping.None;
                }
            }
            if (shader != null)
            {
                if (this.mClippedMat == null)
                {
                    this.mClippedMat = new Material(this.mSharedMat);
                    this.mClippedMat.hideFlags = HideFlags.DontSave;
                }
                this.mClippedMat.shader = shader;
                this.mClippedMat.CopyPropertiesFromMaterial(this.mSharedMat);
            }
            else if (this.mClippedMat != null)
            {
                NGUITools.Destroy(this.mClippedMat);
                this.mClippedMat = null;
            }
        }
        else if (this.mClippedMat != null)
        {
            NGUITools.Destroy(this.mClippedMat);
            this.mClippedMat = null;
        }
        if (this.mDepthPreplaced)
        {
            if (this.mDepthMat == null)
            {
                Shader shader2 = Shader.Find("Unlit/Depth Cutout");
                this.mDepthMat = new Material(shader2);
                this.mDepthMat.hideFlags = HideFlags.DontSave;
            }
            this.mDepthMat.mainTexture = this.mSharedMat.mainTexture;
        }
        else if (this.mDepthMat != null)
        {
            NGUITools.Destroy(this.mDepthMat);
            this.mDepthMat = null;
        }
        Material material = (!(this.mClippedMat != null)) ? this.mSharedMat : this.mClippedMat;
        if (this.mDepthMat != null)
        {
            if (this.mRen.sharedMaterials != null && this.mRen.sharedMaterials.Length == 2 && this.mRen.sharedMaterials[1] == material)
            {
                return;
            }
            this.mRen.sharedMaterials = new Material[]
            {
                this.mDepthMat,
                material
            };
        }
        else if (this.mRen.sharedMaterial != material)
        {
            this.mRen.sharedMaterials = new Material[]
            {
                material
            };
        }
    }

19 Source : Nucleon.cs
with MIT License
from alchemz

void Awake()
    {
        body = GetComponent<Rigidbody>();
        lineRenderer =GetComponent<LineRenderer>();
     
        material= new Material(Shader.Find("Standard"));
        lineRenderer.material = material;


    }

19 Source : AmplifyOcclusionCommon.cs
with MIT License
from BrunoS3D

public static Material CreateMaterialWithShaderName( string aShaderName, bool aThroughErrorMsg )
	{
		var shader = Shader.Find( aShaderName );

		if( shader == null )
		{
			if( aThroughErrorMsg == true )
			{
				Debug.LogErrorFormat( "[AmplifyOcclusion] Cannot find shader: \"{0}\"" +
										" Please contact [email protected]", aShaderName );
			}

			return null;
		}

		return new Material( shader ) { hideFlags = HideFlags.DontSave };
	}

19 Source : PlayerLocationHandler.cs
with MIT License
from CitiesSkylinesMultiplayer

protected override void Handle(PlayerLocationCommand command)
        {
            if (!MultiplayerManager.Instance.IsConnected())
            {
                // Ignore packets while not connected
                return;
            }

            GameObject _playerLocation = GameObject.Find("/PlayerLocation_" + command.PlayerName);
            LineRenderer lineRenderer;
            if (_playerLocation == null)
            {
                _playerLocation = new GameObject("PlayerLocation_" + command.PlayerName);
                lineRenderer = _playerLocation.AddComponent<LineRenderer>();
            }
            else
            {
                lineRenderer = _playerLocation.GetComponent<LineRenderer>();
            }

            // Add Tags for each of the playerMarkers
            _playerLocation.tag = "PlayerPointerObject";

            // Setup LineRenderer
            lineRenderer.material = new Material(Shader.Find("Custom/Particles/Alpha Blended"));
            lineRenderer.startColor = command.PlayerColor;
            lineRenderer.endColor = command.PlayerColor;

            if (!ConnectionPanel.showPlayerPointers)
            {
                lineRenderer.startWidth = 0;
                lineRenderer.endWidth = 0;
            }
            else
            {
                lineRenderer.startWidth = 1;
                lineRenderer.endWidth = 1;
            }

            // Set cube rotation to match the camera
            Transform playerLocation = _playerLocation.transform;
            playerLocation.position = command.PlayerCameraPosition;
            playerLocation.rotation = command.PlayerCameraRotation;

            // Make the LineRendered shoot forward (in the direction of the cube)
            Vector3 position = playerLocation.position;
            lineRenderer.SetPosition(0, position);
            lineRenderer.SetPosition(1, playerLocation.forward * 10000 + position);
        }

19 Source : SoftMaskableEditor.cs
with GNU General Public License v3.0
from Cytoid

void OnEnable ()
		{
			_spMaskInteraction = serializedObject.FindProperty("m_MaskInteraction");
			_custom = (maskInteraction == MaskInteraction.Custom);

			ClearMaterialEditors ();

			_shader = Shader.Find ("TextMeshPro/Distance Field (SoftMaskable)");
			_mobileShader = Shader.Find ("TextMeshPro/Mobile/Distance Field (SoftMaskable)");
			_spriteShader = Shader.Find ("TextMeshPro/Sprite (SoftMaskable)");

			if(s_TypeTMPro != null)
			{
				s_PiFontSharedMaterial = s_TypeTMPro.GetProperty ("fontSharedMaterial");
				s_PiSpritereplacedet = s_TypeTMPro.GetProperty ("spritereplacedet");
				s_PiRichText = s_TypeTMPro.GetProperty ("richText");
				s_PiText = s_TypeTMPro.GetProperty ("text");
				s_FiMaterial = s_TypeTMP_Spritereplacedet.GetField ("material");
				s_PiFontSharedMaterials = s_TypeTMPro.GetProperty ("fontSharedMaterials");
				s_miGetSpritereplacedet = s_TypeTMProSettings.GetMethod ("GetSpritereplacedet", BindingFlags.Static | BindingFlags.Public);

				s_PiDefaultFontreplacedetPath = s_TypeTMProSettings.GetProperty ("defaultFontreplacedetPath", BindingFlags.Static | BindingFlags.Public);
				s_PiDefaultSpritereplacedetPath = s_TypeTMProSettings.GetProperty ("defaultSpritereplacedetPath", BindingFlags.Static | BindingFlags.Public);
			}

			s_MaskWarning = new GUIContent(EditorGUIUtility.FindTexture("console.warnicon.sml"), "This component is not SoftMask. Use SoftMask instead of Mask.");
		}

19 Source : UIDissolveEditor.cs
with GNU General Public License v3.0
from Cytoid

protected override void OnEnable()
		{
			base.OnEnable ();

			_spMaterial = serializedObject.FindProperty("m_EffectMaterial");
			_spEffectFactor = serializedObject.FindProperty("m_EffectFactor");
			_spEffectArea = serializedObject.FindProperty("m_EffectArea");
			_spKeepAspectRatio = serializedObject.FindProperty("m_KeepAspectRatio");
			_spWidth = serializedObject.FindProperty("m_Width");
			_spColor = serializedObject.FindProperty("m_Color");
			_spSoftness = serializedObject.FindProperty("m_Softness");
			_spColorMode = serializedObject.FindProperty("m_ColorMode");
			_spNoiseTexture = serializedObject.FindProperty("m_NoiseTexture");
			_spKeepAspectRatio = serializedObject.FindProperty("m_KeepAspectRatio");
			_spReverse = serializedObject.FindProperty("m_Reverse");
			var player = serializedObject.FindProperty("m_Player");
			_spPlay = player.FindPropertyRelative("play");
			_spDuration = player.FindPropertyRelative("duration");
			_spInitialPlayDelay = player.FindPropertyRelative("initialPlayDelay");
			_spLoop = player.FindPropertyRelative("loop");
			_spLoopDelay = player.FindPropertyRelative("loopDelay");
			_spUpdateMode = player.FindPropertyRelative("updateMode");

			s_NoiseTexId = Shader.PropertyToID ("_NoiseTex");

			_shader = Shader.Find ("TextMeshPro/Distance Field (UIDissolve)");
			_mobileShader = Shader.Find ("TextMeshPro/Mobile/Distance Field (UIDissolve)");
			_spriteShader = Shader.Find ("TextMeshPro/Sprite (UIDissolve)");
		}

19 Source : UIEffectEditor.cs
with GNU General Public License v3.0
from Cytoid

protected override void OnEnable()
		{
			base.OnEnable ();

			_shader = Shader.Find ("TextMeshPro/Distance Field (UIEffect)");
			_mobileShader = Shader.Find ("TextMeshPro/Mobile/Distance Field (UIEffect)");
			_spriteShader = Shader.Find ("TextMeshPro/Sprite (UIEffect)");
		}

19 Source : UIHsvModifierEditor.cs
with GNU General Public License v3.0
from Cytoid

protected override void OnEnable()
		{
			base.OnEnable ();

			_spMaterial = serializedObject.FindProperty("m_EffectMaterial");
			_spTargetColor = serializedObject.FindProperty("m_TargetColor");
			_spRange = serializedObject.FindProperty("m_Range");
			_spHue = serializedObject.FindProperty("m_Hue");
			_spSaturation = serializedObject.FindProperty("m_Saturation");
			_spValue = serializedObject.FindProperty("m_Value");

			_shader = Shader.Find ("TextMeshPro/Distance Field (UIHsvModifier)");
			_mobileShader = Shader.Find ("TextMeshPro/Mobile/Distance Field (UIHsvModifier)");
			_spriteShader = Shader.Find ("TextMeshPro/Sprite (UIHsvModifier)");
		}

19 Source : UIShinyEditor.cs
with GNU General Public License v3.0
from Cytoid

protected override void OnEnable()
		{
			base.OnEnable ();

			_spMaterial = serializedObject.FindProperty("m_EffectMaterial");
			_spEffectFactor = serializedObject.FindProperty("m_EffectFactor");
			_spEffectArea = serializedObject.FindProperty("m_EffectArea");
			_spWidth = serializedObject.FindProperty("m_Width");
			_spRotation = serializedObject.FindProperty("m_Rotation");
			_spSoftness = serializedObject.FindProperty("m_Softness");
			_spBrightness = serializedObject.FindProperty("m_Brightness");
			_spGloss = serializedObject.FindProperty("m_Gloss");
			var player = serializedObject.FindProperty("m_Player");
			_spPlay = player.FindPropertyRelative("play");
			_spDuration = player.FindPropertyRelative("duration");
			_spInitialPlayDelay = player.FindPropertyRelative("initialPlayDelay");
			_spLoop = player.FindPropertyRelative("loop");
			_spLoopDelay = player.FindPropertyRelative("loopDelay");
			_spUpdateMode = player.FindPropertyRelative("updateMode");


			_shader = Shader.Find ("TextMeshPro/Distance Field (UIShiny)");
			_mobileShader = Shader.Find ("TextMeshPro/Mobile/Distance Field (UIShiny)");
			_spriteShader = Shader.Find ("TextMeshPro/Sprite (UIShiny)");
		}

19 Source : UITransitionEffectEditor.cs
with GNU General Public License v3.0
from Cytoid

protected override void OnEnable()
		{
			base.OnEnable();

			_spMaterial = serializedObject.FindProperty("m_EffectMaterial");
			_spEffectMode = serializedObject.FindProperty("m_EffectMode");
			_spEffectFactor = serializedObject.FindProperty("m_EffectFactor");
			_spEffectArea = serializedObject.FindProperty("m_EffectArea");
			_spKeepAspectRatio = serializedObject.FindProperty("m_KeepAspectRatio");
			_spDissolveWidth = serializedObject.FindProperty("m_DissolveWidth");
			_spDissolveSoftness = serializedObject.FindProperty("m_DissolveSoftness");
			_spDissolveColor = serializedObject.FindProperty("m_DissolveColor");
			_spTransitionTexture = serializedObject.FindProperty("m_TransitionTexture");
			var player = serializedObject.FindProperty("m_Player");
			_spPlay = player.FindPropertyRelative("play");
			_spDuration = player.FindPropertyRelative("duration");
			_spInitialPlayDelay = player.FindPropertyRelative("initialPlayDelay");
			_spLoop = player.FindPropertyRelative("loop");
			_spLoopDelay = player.FindPropertyRelative("loopDelay");
			_spUpdateMode = player.FindPropertyRelative("updateMode");
			_spPreplacedRayOnHidden = serializedObject.FindProperty("m_PreplacedRayOnHidden");

			s_NoiseTexId = Shader.PropertyToID("_NoiseTex");

			_shader = Shader.Find("TextMeshPro/Distance Field (UITransition)");
			_mobileShader = Shader.Find("TextMeshPro/Mobile/Distance Field (UITransition)");
			_spriteShader = Shader.Find("TextMeshPro/Sprite (UITransition)");
		}

19 Source : ABModelTests.cs
with GNU General Public License v3.0
from Cytoid

[Test]
        public static void HandleDedupeBundles_MovesDuplicatedreplacedets_ToNewBundle()
        {
            string bundle1PrefabInstanceName = "Bundle1Prefab";
            string bundle2PrefabInstanceName = "Bundle2Prefab";

            string bundle1Name = "bundle1";
            string bundle2Name = "bundle2";

            List<string> listOfreplacedets = new List<string>();
            listOfreplacedets.Add(TestUtil.CreatePrefabWithBundleAndVariantName(bundle1Name, "", bundle1PrefabInstanceName));
            listOfreplacedets.Add(TestUtil.CreatePrefabWithBundleAndVariantName(bundle2Name, "", bundle2PrefabInstanceName));

            BundleDataInfo bundle1DataInfo = new BundleDataInfo(bundle1Name, ABModelUtil.Root);
            BundleDataInfo bundle2DataInfo = new BundleDataInfo(bundle2Name, ABModelUtil.Root);

            ABModelUtil.Root.AddChild(bundle1DataInfo);
            ABModelUtil.Root.AddChild(bundle2DataInfo);

            bundle1DataInfo.RefreshreplacedetList();
            bundle2DataInfo.RefreshreplacedetList();

            //Need a material with no replacedigned bundle so it'll be pulled into both bundles
            string materialPath = "replacedets/material.mat";
            Material mat = new Material(Shader.Find("Diffuse"));
            replacedetDatabase.Createreplacedet(mat, materialPath);
            listOfreplacedets.Add(materialPath);
            //

            Model.Refresh();

            TestUtil.ExecuteCodeAndCleanupreplacedets(() =>
            {
                AddMaterialsToMultipleObjects(new string[] { bundle1PrefabInstanceName, bundle2PrefabInstanceName }, listOfreplacedets, mat);
                Model.HandleDedupeBundles(new BundleInfo[] { bundle1DataInfo, bundle2DataInfo }, false);
            //This checks to make sure that a newbundle was automatically created since we dont' set this up anywhere else.
            replacedert.IsTrue(replacedetDatabase.GetAllreplacedetBundleNames().Contains("newbundle"));

            }, listOfreplacedets);
        }

19 Source : SleekRenderPostProcess.cs
with GNU General Public License v3.0
from Cytoid

private void CreateResources()
        {
            _mainCamera = GetComponent<Camera>();

            var downsampleShader = Shader.Find("Sleek Render/Post Process/Downsample Brightpreplaced");
            var horizontalBlurShader = Shader.Find("Sleek Render/Post Process/Horizontal Blur");
            var verticalBlurShader = Shader.Find("Sleek Render/Post Process/Vertical Blur");
            var composeShader = Shader.Find("Sleek Render/Post Process/Compose");
            var preComposeShader = Shader.Find("Sleek Render/Post Process/PreCompose");

            _downsampleMaterial = new Material(downsampleShader);
            _horizontalBlurMaterial = new Material(horizontalBlurShader);
            _verticalBlurMaterial = new Material(verticalBlurShader);
            _preComposeMaterial = new Material(preComposeShader);
            _composeMaterial = new Material(composeShader);

            _currentCameraPixelWidth = Mathf.RoundToInt(_mainCamera.pixelWidth);
            _currentCameraPixelHeight = Mathf.RoundToInt(_mainCamera.pixelHeight);

            // Point for future main render target size changing
            int width = _currentCameraPixelWidth;
            int height = _currentCameraPixelHeight;

            // Capping max base texture height in pixels
            // We usually don't need extra pixels for precompose and blur preplacedes
            var maxHeight = Mathf.Min(height, 720);
            var ratio = (float)maxHeight / height;

            // Constant used to make the bloom look completely uniform on square or circle objects
            int blurHeight = settings.bloomTextureHeight;
            int blurWidth = settings.preserveAspectRatio ? Mathf.RoundToInt(blurHeight * GetCurrentAspect(_mainCamera)) : settings.bloomTextureWidth;

            // Downsampling texture size (downscale + brightpreplaced and precompose)
            int downsampleWidth = Mathf.RoundToInt((width * ratio) / 5f);
            int downsampleHeight = Mathf.RoundToInt((height * ratio) / 5f);

            _downsampledBrightpreplacedTexture = CreateTransientRenderTexture("Bloom Downsample Preplaced", downsampleWidth, downsampleHeight);
            _brightPreplacedBlurTexture = CreateTransientRenderTexture("Pre Bloom", blurWidth, blurHeight);
            _horizontalBlurTexture = CreateTransientRenderTexture("Horizontal Blur", blurWidth, blurHeight);
            _verticalBlurTexture = CreateTransientRenderTexture("Vertical Blur", blurWidth, blurHeight);
            _preComposeTexture = CreateTransientRenderTexture("Pre Compose", downsampleWidth, downsampleHeight);

            _verticalBlurMaterial.SetTexture(Uniforms._MainTex, _downsampledBrightpreplacedTexture);
            _verticalBlurMaterial.SetTexture(Uniforms._BloomTex, _horizontalBlurTexture);

            var xSpread = 1 / (float)blurWidth;
            var ySpread = 1 / (float)blurHeight;
            var blurTexelSize = new Vector4(xSpread, ySpread);
            _verticalBlurMaterial.SetVector(Uniforms._TexelSize, blurTexelSize);
            _horizontalBlurMaterial.SetVector(Uniforms._TexelSize, blurTexelSize);

            _preComposeMaterial.SetTexture(Uniforms._BloomTex, _verticalBlurTexture);

            var downsampleTexelSize = new Vector4(1f / _downsampledBrightpreplacedTexture.width, 1f / _downsampledBrightpreplacedTexture.height);
            _downsampleMaterial.SetVector(Uniforms._TexelSize, downsampleTexelSize);

            _composeMaterial.SetTexture(Uniforms._PreComposeTex, _preComposeTexture);
            _composeMaterial.SetVector(Uniforms._LuminanceConst, new Vector4(0.2126f, 0.7152f, 0.0722f, 0f));

            _fullscreenQuadMesh = CreateScreenSpaceQuadMesh();

            _isColorizeAlreadyEnabled = false;
            _isBloomAlreadyEnabled = false;
            _isVignetteAlreadyEnabled = false;
            _isContrastAndBrightnessAlreadyEnabled = false;
        }

19 Source : SteamVR_LaserPointer.cs
with MIT License
from dag10

void Start ()
    {
        holder = new GameObject();
        holder.transform.parent = this.transform;
        holder.transform.localPosition = Vector3.zero;
		holder.transform.localRotation = Quaternion.idenreplacedy;

		pointer = GameObject.CreatePrimitive(PrimitiveType.Cube);
        pointer.transform.parent = holder.transform;
        pointer.transform.localScale = new Vector3(thickness, thickness, 100f);
        pointer.transform.localPosition = new Vector3(0f, 0f, 50f);
		pointer.transform.localRotation = Quaternion.idenreplacedy;
		BoxCollider collider = pointer.GetComponent<BoxCollider>();
        if (addRigidBody)
        {
            if (collider)
            {
                collider.isTrigger = true;
            }
            Rigidbody rigidBody = pointer.AddComponent<Rigidbody>();
            rigidBody.isKinematic = true;
        }
        else
        {
            if(collider)
            {
                Object.Destroy(collider);
            }
        }
        Material newMaterial = new Material(Shader.Find("Unlit/Color"));
        newMaterial.SetColor("_Color", color);
        pointer.GetComponent<MeshRenderer>().material = newMaterial;
	}

19 Source : SteamVR_ExternalCamera.cs
with MIT License
from dag10

public void AttachToCamera(SteamVR_Camera vrcam)
	{
		if (target == vrcam.head)
			return;

		target = vrcam.head;

		var root = transform.parent;
		var origin = vrcam.head.parent;
		root.parent = origin;
		root.localPosition = Vector3.zero;
		root.localRotation = Quaternion.idenreplacedy;
		root.localScale = Vector3.one;

		// Make a copy of the eye camera to pick up any camera fx.
		vrcam.enabled = false;
		var go = Instantiate(vrcam.gameObject);
		vrcam.enabled = true;
		go.name = "camera";

		DestroyImmediate(go.GetComponent<SteamVR_Camera>());

		cam = go.GetComponent<Camera>();
		cam.fieldOfView = config.fov;
		cam.useOcclusionCulling = false;
		cam.enabled = false; // manually rendered

		colorMat = new Material(Shader.Find("Custom/SteamVR_ColorOut"));
		alphaMat = new Material(Shader.Find("Custom/SteamVR_AlphaOut"));
		clipMaterial = new Material(Shader.Find("Custom/SteamVR_ClearAll"));

		var offset = go.transform;
		offset.parent = transform;
		offset.localPosition = new Vector3(config.x, config.y, config.z);
		offset.localRotation = Quaternion.Euler(config.rx, config.ry, config.rz);
		offset.localScale = Vector3.one;

		// Strip children of cloned object (AudioListener in particular).
		while (offset.childCount > 0)
			DestroyImmediate(offset.GetChild(0).gameObject);

		// Setup clipping quad (using camera clip causes problems with shadows).
		clipQuad = GameObject.CreatePrimitive(PrimitiveType.Quad);
		clipQuad.name = "ClipQuad";
		DestroyImmediate(clipQuad.GetComponent<MeshCollider>());

		var clipRenderer = clipQuad.GetComponent<MeshRenderer>();
		clipRenderer.material = clipMaterial;
		clipRenderer.shadowCastingMode = ShadowCastingMode.Off;
		clipRenderer.receiveShadows = false;
		clipRenderer.lightProbeUsage = LightProbeUsage.Off;
		clipRenderer.reflectionProbeUsage = ReflectionProbeUsage.Off;

		var clipTransform = clipQuad.transform;
		clipTransform.parent = offset;
		clipTransform.localScale = new Vector3(1000.0f, 1000.0f, 1.0f);
		clipTransform.localRotation = Quaternion.idenreplacedy;

		clipQuad.SetActive(false);
	}

19 Source : SteamVR_Fade.cs
with MIT License
from dag10

void OnEnable()
	{
		if (fadeMaterial == null)
		{
			fadeMaterial = new Material(Shader.Find("Custom/SteamVR_Fade"));
			fadeMaterialColorID = Shader.PropertyToID("fadeColor");
		}

		SteamVR_Events.Fade.Listen(OnStartFade);
		SteamVR_Events.FadeReady.Send();
	}

19 Source : SteamVR_PlayArea.cs
with MIT License
from dag10

public void BuildMesh()
	{
		var rect = new HmdQuad_t();
		if ( !GetBounds( size, ref rect ) )
			return;

		var corners = new HmdVector3_t[] { rect.vCorners0, rect.vCorners1, rect.vCorners2, rect.vCorners3 };

		vertices = new Vector3[corners.Length * 2];
		for (int i = 0; i < corners.Length; i++)
		{
			var c = corners[i];
			vertices[i] = new Vector3(c.v0, 0.01f, c.v2);
		}

		if (borderThickness == 0.0f)
		{
			GetComponent<MeshFilter>().mesh = null;
			return;
		}

		for (int i = 0; i < corners.Length; i++)
		{
			int next = (i + 1) % corners.Length;
			int prev = (i + corners.Length - 1) % corners.Length;

			var nextSegment = (vertices[next] - vertices[i]).normalized;
			var prevSegment = (vertices[prev] - vertices[i]).normalized;

			var vert = vertices[i];
			vert += Vector3.Cross(nextSegment, Vector3.up) * borderThickness;
			vert += Vector3.Cross(prevSegment, Vector3.down) * borderThickness;

			vertices[corners.Length + i] = vert;
		}

		var triangles = new int[]
		{
			0, 4, 1,
			1, 4, 5,
			1, 5, 2,
			2, 5, 6,
			2, 6, 3,
			3, 6, 7,
			3, 7, 0,
			0, 7, 4
		};

		var uv = new Vector2[]
		{
			new Vector2(0.0f, 0.0f),
			new Vector2(1.0f, 0.0f),
			new Vector2(0.0f, 0.0f),
			new Vector2(1.0f, 0.0f),
			new Vector2(0.0f, 1.0f),
			new Vector2(1.0f, 1.0f),
			new Vector2(0.0f, 1.0f),
			new Vector2(1.0f, 1.0f)
		};

		var colors = new Color[]
		{
			color,
			color,
			color,
			color,
			new Color(color.r, color.g, color.b, 0.0f),
			new Color(color.r, color.g, color.b, 0.0f),
			new Color(color.r, color.g, color.b, 0.0f),
			new Color(color.r, color.g, color.b, 0.0f)
		};

		var mesh = new Mesh();
		GetComponent<MeshFilter>().mesh = mesh;
		mesh.vertices = vertices;
		mesh.uv = uv;
		mesh.colors = colors;
		mesh.triangles = triangles;

		var renderer = GetComponent<MeshRenderer>();
		renderer.material = new Material(Shader.Find("Sprites/Default"));
		renderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
		renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
		renderer.receiveShadows = false;
		renderer.lightProbeUsage = LightProbeUsage.Off;
	}

19 Source : SteamVR_RenderModel.cs
with MIT License
from dag10

RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
	{
        var pRenderModel = System.IntPtr.Zero;

		EVRRenderModelError error;
		while ( true )
		{
			error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
			if (error != EVRRenderModelError.Loading)
				break;
#if UNITY_STANDALONE

			System.Threading.Thread.Sleep(1);
#endif
		}

		if (error != EVRRenderModelError.None)
		{
			Debug.LogError(string.Format("Failed to load render model {0} - {1}", renderModelName, error.ToString()));
			return null;
		}

        var renderModel = MarshalRenderModel(pRenderModel);

		var vertices = new Vector3[renderModel.unVertexCount];
		var normals = new Vector3[renderModel.unVertexCount];
		var uv = new Vector2[renderModel.unVertexCount];

		var type = typeof(RenderModel_Vertex_t);
		for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
		{
			var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
			var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

			vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
			normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
			uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
		}

		int indexCount = (int)renderModel.unTriangleCount * 3;
		var indices = new short[indexCount];
		Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

		var triangles = new int[indexCount];
		for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
		{
			triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
			triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
			triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
		}

		var mesh = new Mesh();
		mesh.vertices = vertices;
		mesh.normals = normals;
		mesh.uv = uv;
		mesh.triangles = triangles;

#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
		mesh.Optimize();
#endif
		//mesh.hideFlags = HideFlags.DontUnloadUnusedreplacedet;

		// Check cache before loading texture.
		var material = materials[renderModel.diffuseTextureId] as Material;
		if (material == null || material.mainTexture == null)
		{
			var pDiffuseTexture = System.IntPtr.Zero;

			while (true)
			{
				error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
				if (error != EVRRenderModelError.Loading)
					break;
#if UNITY_STANDALONE

				System.Threading.Thread.Sleep(1);
#endif
			}

			if (error == EVRRenderModelError.None)
			{
				var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
				var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.ARGB32, false);
				if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
				{
					texture.Apply();

					while (true)
					{
						error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texture.GetNativeTexturePtr());
						if (error != EVRRenderModelError.Loading)
							break;
#if UNITY_STANDALONE
    					System.Threading.Thread.Sleep(1);
#endif
					}
				}
				else
				{
					var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
					Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

					var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
					int iColor = 0;
					for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
					{
						for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
						{
							var r = textureMapData[iColor++];
							var g = textureMapData[iColor++];
							var b = textureMapData[iColor++];
							var a = textureMapData[iColor++];
							colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
						}
					}

					texture.SetPixels32(colors);
					texture.Apply();
				}

				material = new Material(shader != null ? shader : Shader.Find("Standard"));
				material.mainTexture = texture;
				//material.hideFlags = HideFlags.DontUnloadUnusedreplacedet;

				materials[renderModel.diffuseTextureId] = material;

				renderModels.FreeTexture(pDiffuseTexture);
			}
			else
			{
				Debug.Log("Failed to load render model texture for render model " + renderModelName);
			}
		}

		// Delay freeing when we can since we'll often get multiple requests for the same model right
		// after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
		if (!Application.isPlaying)
			renderModels.FreeRenderModel(pRenderModel);
		else
#endif
			StartCoroutine(FreeRenderModel(pRenderModel));

		return new RenderModel(mesh, material);
	}

19 Source : SteamVR_SphericalProjection.cs
with MIT License
from dag10

public void Set(Vector3 N,
		float phi0, float phi1, float theta0, float theta1, // in degrees
		Vector3 uAxis, Vector3 uOrigin, float uScale,
		Vector3 vAxis, Vector3 vOrigin, float vScale)
	{
		if (material == null)
			material = new Material(Shader.Find("Custom/SteamVR_SphericalProjection"));

		material.SetVector("_N", new Vector4(N.x, N.y, N.z));
		material.SetFloat("_Phi0", phi0 * Mathf.Deg2Rad);
		material.SetFloat("_Phi1", phi1 * Mathf.Deg2Rad);
		material.SetFloat("_Theta0", theta0 * Mathf.Deg2Rad + Mathf.PI / 2);
		material.SetFloat("_Theta1", theta1 * Mathf.Deg2Rad + Mathf.PI / 2);
		material.SetVector("_UAxis", uAxis);
		material.SetVector("_VAxis", vAxis);
		material.SetVector("_UOrigin", uOrigin);
		material.SetVector("_VOrigin", vOrigin);
		material.SetFloat("_UScale", uScale);
		material.SetFloat("_VScale", vScale);
	}

19 Source : CoSimulationDebugger.cs
with MIT License
from Daimler

private void ShowSceneManipulations(List<MSceneManipulation> sceneManipulations)
        {

            for (int i = sceneManipulationObjects.Count - 1; i >= 0; i--)
            {
                sceneManipulationObjects[i].SetActive(false);
            }

            int index = 0;

            foreach (MSceneManipulation sceneManipulation in sceneManipulations)
            {
                if (sceneManipulation.Transforms !=null)
                {

                    foreach(MTransformManipulation tm in sceneManipulation.Transforms)
                    {
                        GameObject p = null;
                        if (index < sceneManipulationObjects.Count)
                        {
                            p = sceneManipulationObjects[index];
                            p.SetActive(true);

                            try
                            {
                                //Apply the scene manipulation
                                UnitySceneAccess.Instance.ApplyManipulations(new List<MSceneManipulation>() { new MSceneManipulation() { Transforms = new List<MTransformManipulation>() { tm } } });
                            }
                            catch (System.Exception)
                            {
                                //It might be the case that the ID is invalid for the current scene
                            }
                        }
                        else
                        {
                            p = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                            p.GetComponent<Renderer>().material = new Material(Shader.Find("Standard"));
                            p.GetComponent<Renderer>().material.color = Color.cyan;
                            p.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
                            sceneManipulationObjects.Add(p);
                        }
                    

                        p.transform.position = new Vector3((float)tm.Position.X, (float)tm.Position.Y, (float)tm.Position.Z);


                        index++;
                    }
                }
            }
        }

19 Source : MMISceneObject.cs
with MIT License
from Daimler

protected virtual void OnDrawGizmos()
        {
            //Visualize the coordiante system if desired
            if (this.ShowCoordinateSystem)
            {
                Gizmos.color = Color.blue;
                Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.forward * 0.1f);
                Gizmos.color = Color.green;
                Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.up * 0.05f);
                Gizmos.color = Color.red;
                Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.right * 0.05f);
            }

            //Visualize the velocity if defined
            if (this.Velocity.magnitude > 0)
            {
                Gizmos.color = Color.green;
                Gizmos.DrawLine(this.transform.position, this.transform.position + this.Velocity.normalized * 0.5f);
            }

            //Optionally override the color
            if (this.OverrideColor)
            {
                if (this.GetComponent<Renderer>() != null)
                {
                    if(this.GetComponent<Renderer>().sharedMaterial.color != this.Color)                
                        this.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Standard"));

                    //replacedign the color
                    this.GetComponent<Renderer>().sharedMaterial.color = this.Color;
                }
            }
        }

19 Source : DrawingUtils.cs
with MIT License
from Daimler

public static GameObject DrawAvatarPosture(MAvatarPosture posture)
        {
            GameObject root = new GameObject();

            Dictionary<string, GameObject> transforms = new Dictionary<string, GameObject>();

            if (posture == null || posture.Joints == null)
                return root;

            foreach (MJoint boneTransform in posture.Joints)
            {
                //Create an empty gameobject for each bone
                GameObject joint = new GameObject(boneTransform.ID);
                joint.transform.position = boneTransform.Position.ToVector3();
                joint.transform.rotation = boneTransform.Rotation.ToQuaternion();

                transforms.Add(joint.name, joint);
            }


            foreach (MJoint boneTransform in posture.Joints)
            {
                GameObject joint = transforms[boneTransform.ID];

                //Compute the global position
                if (boneTransform.Parent != null && transforms.ContainsKey(boneTransform.Parent))
                {
                    joint.transform.position = transforms[boneTransform.Parent].transform.TransformPoint(joint.transform.position);
                    joint.transform.rotation = transforms[boneTransform.Parent].transform.rotation * joint.transform.rotation;

                    joint.transform.parent = transforms[boneTransform.Parent].transform;
                }
                else
                {
                    joint.transform.parent = root.transform;
                }
            }

            foreach (GameObject gameObject in transforms.Values)
            {
                if (gameObject.transform.parent != null && transforms.ContainsKey(gameObject.transform.parent.name))
                {
                    var lr = gameObject.AddComponent<LineRenderer>();
                    lr.material.shader = Shader.Find("Particles/Standard Surface");
                    lr.SetPositions(new Vector3[] { gameObject.transform.parent.position, gameObject.transform.position });
                    lr.startWidth = 0.02f;
                    lr.endWidth = 0.02f;
                    lr.startColor = Color.red;
                    lr.endColor = Color.blue;
                }
            }

            return root;
        }

19 Source : CoSimulationDebugger.cs
with MIT License
from Daimler

private void ShowConstraints(List<MConstraint> constraints)
        {

            for(int i= constraintObjects.Count-1; i >= 0; i--)
            {
                constraintObjects[i].SetActive(false);
            }

            int index = 0;

            foreach(MConstraint constraint in constraints)
            {
                if(constraint.JointConstraint != null)
                {
                    MJointConstraint endeffectorConstraint = constraint.JointConstraint;

                    if (endeffectorConstraint.GeometryConstraint != null)
                    {
                        MTranslationConstraint posConstraint = endeffectorConstraint.GeometryConstraint.TranslationConstraint;

                        GameObject p = null;
                        if (index < constraintObjects.Count)
                        {
                            p = constraintObjects[index];
                            p.SetActive(true);
                        }
                        else
                        {
                            p = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                            p.GetComponent<Renderer>().material = new Material(Shader.Find("Standard"));
                            p.GetComponent<Renderer>().material.color = Color.red;
                            p.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
                            constraintObjects.Add(p);
                        }

                        index++;


                        if(endeffectorConstraint.GeometryConstraint.ParentToConstraint !=null)
                            p.transform.position = endeffectorConstraint.GeometryConstraint.ParentToConstraint.Position.ToVector3();
                    }
                }
            }
        }

19 Source : CompanionAI.cs
with MIT License
from Donut-Studios

protected void Start()
	{
		CoreAIStart();
		rend = (GameObject.Find("chr_janitor1")).GetComponent<Renderer>();
		normal = Shader.Find("Diffuse");
		glowing = Shader.Find("Self-Illumin/Diffuse");
		this.setActive(false);
        state = Statetype.FOLLOWING;
	}

19 Source : VookaSeatedMode.cs
with MIT License
from Eusth

private void InstallVignetting()
        {
            _Vignette = VR.Camera.gameObject.AddComponent<VignetteAndChromaticAberration>();
            _Vignette.vignetteShader = Shader.Find("Hidden/Vignetting");
            _Vignette.separableBlurShader = Shader.Find("Hidden/SeparableBlur");
            _Vignette.chromAberrationShader = Shader.Find("Hidden/ChromaticAberration");

            _Vignette.chromaticAberration = 0.0f;
            _Vignette.intensity = MIN_VIGNETTING;

            VR.Camera.FixEffectOrder();
        }

19 Source : GvrPostRender.cs
with MIT License
from harshitjuneja

void Awake() {
    cam = GetComponent<Camera>();
    Reset();
    meshMaterial = new Material(Shader.Find("GoogleVR/UnlitTexture"));
    uiMaterial = new Material(Shader.Find("GoogleVR/SolidColor"));
    uiMaterial.color = new Color(0.8f, 0.8f, 0.8f);
    if (!Application.isEditor) {
      ComputeUIMatrix();
    }
  }

19 Source : StereoRenderEffect.cs
with MIT License
from harshitjuneja

void Start() {
    material = new Material(Shader.Find("GoogleVR/UnlitTexture"));
#if UNITY_5_6_OR_NEWER
    fullRect = (eye == GvrViewer.Eye.Left ? new Rect (0, 0, 0.5f, 1) : new Rect (0.5f, 0, 0.5f, 1));
#endif

  }

19 Source : ImportTiled2Unity.Xml.cs
with MIT License
from HDNua

private UnityEngine.Material CreateMaterialFromXml(XElement xml, Tiled2Unity.ImportBehaviour importComponent)
        {
            // Does this material support alpha color key?
            bool useColorKey = xml.Attribute("alphaColorKey") != null;
            bool usesDepthShader = ImportUtils.GetAttributeAsBoolean(xml, "usesDepthShaders", false);

            // Determine which shader we sould be using
            string shaderName = "Tiled2Unity/";

            // Are we using depth shaders?
            if (usesDepthShader)
            {
                shaderName += "Depth";
            }
            else
            {
                shaderName += "Default";
            }

            // Are we using color key shaders?
            Color keyColor = Color.black;
            if (useColorKey)
            {
                keyColor = ImportUtils.GetAttributeAsColor(xml, "alphaColorKey");
                shaderName += " Color Key";
            }

            // Are we using instanced shaders?
#if UNITY_5_6_OR_NEWER
            shaderName += " (Instanced)";
#endif

            // Try creating the material with the right shader. Fall back to the built-in Sprites/Default shader if there's a problem.
            UnityEngine.Material material = null;
            try
            {
                material = new UnityEngine.Material(UnityEngine.Shader.Find(shaderName));
            }
            catch (Exception e)
            {
                importComponent.RecordError("Error creating material with shader '{0}'. {1}", shaderName, e.Message);
            }

            if (material == null)
            {
                importComponent.RecordWarning("Using default sprite shader for material");
                material = new UnityEngine.Material(UnityEngine.Shader.Find("Sprites/Default"));
            }

            if (useColorKey)
            {
                material.SetColor("_AlphaColorKey", keyColor);
            }

#if UNITY_5_6_OR_NEWER
            material.enableInstancing = true;
#endif

            return material;
        }

19 Source : Example.cs
with GNU General Public License v3.0
from KleskBY

void Update()
    {
        float minDist = 99999;
        Vector2 AimTarget = Vector2.zero;
        try
        {
            foreach (GameObject go in badguys)
            {
                Transform[] allChildren = go.transform.GetComponentsInChildren<Transform>();
                foreach (Transform child in allChildren)
                {
                    if (child.name == bone) //NPC_Spine1 "NPC_Neck"
                    {
                        var replaced = Camera.main.WorldToScreenPoint(child.transform.position);
                        if (replaced.z > -8)
                        {
                            float dist = System.Math.Abs(Vector2.Distance(new Vector2(replaced.x, Screen.height - replaced.y), new Vector2((Screen.width / 2), (Screen.height / 2))));
                            if (dist < 300) //in fov
                            {
                                if (dist < minDist)
                                {
                                    minDist = dist;
                                    AimTarget = new Vector2(replaced.x, Screen.height - replaced.y);
                                }
                            }
                        }
                    }
                }
            }
            if(AimTarget != Vector2.zero)
            {
                double DistX = AimTarget.x - Screen.width / 2.0f;
                double DistY = AimTarget.y - Screen.height / 2.0f;

                //aimsmooth
                DistX /= smooth;
                DistY /= smooth;

                //if aimkey is pressed
                if(!menu)
                if (Input.GetKey(aimkey)) mouse_event(0x0001, (int)DistX, (int)DistY, 0, 0);
            }
        }
         catch { }

        /////////MENU HOTKEY////////////
        if (Input.GetKeyDown(KeyCode.Insert)) menu = !menu;

        ////////////////ENEMY LIST UPDATE/////////
        try
        {
            if (one <= two)
            {
                one = one - 1;
                if (one == two - 1)
                {
                    foreach (GameObject go in GameObject.FindObjectsOfType(typeof(GameObject)))
                    {
                        if (go.name.Contains(nameToAdd))
                        {
                            var distance = Vector3.Distance(Camera.main.transform.position, go.transform.position);
                            if (distance > 2)
                            {
                                if (!badguys.Contains(go))
                                {
                                    var rend = go.GetComponentInChildren<Renderer>();
                                    if (rend.material.name.Contains("S") || rend.material.name.Contains("B")) //"p0/Bumped Specular Mask" "p0/Reflective/Bumped Specular Mask W"
                                    {
                                        badguys.Add(go);
                                        if (wallhack)
                                        {
                                            var rend2 = go.GetComponentsInChildren<Renderer>();
                                            chams.Add(go);
                                            foreach (Renderer renderer in rend2)
                                            {
                                                DefaultShader = renderer.material.shader;
                                                renderer.material.shader = Shader.Find("Hidden/Internal-GUITexture");
                                            }
                                        }
                                    }
                                    else if (distance > 12) badguys.Add(go);
                                    else GameObject.Destroy(go);
                                }
                            }
                        }
                    }
                }
            }
            if (one <= 0)
            {
                badguys.Clear();
                if (wallhack)
                {
                    try
                    {
                        foreach (GameObject gameObj in chams)
                        {
                            if (gameObj != null)
                            {
                                var rend = gameObj.GetComponentsInChildren<Renderer>();
                                foreach (Renderer renderer in rend) renderer.material.shader = DefaultShader;
                            }
                        }
                    }
                    catch { }
                }
                one = two;
            }
        }
        catch { }
    }

19 Source : BlockPool.cs
with MIT License
from Lallassu

void Start () {
        for(int i = 0; i < poolSize; i++) {
            GameObject c = GameObject.CreatePrimitive (PrimitiveType.Cube);
            c.transform.position = new Vector3 (Random.Range(70, 150), Random.Range(0, 100), Random.Range(-10.0f, -30.0f));
            c.transform.localScale.Set (1, 1, 1);
            c.GetComponent<MeshRenderer>().material.shader = Shader.Find("Standard (Vertex Color)");
            c.GetComponent<MeshRenderer>().material.EnableKeyword("_VERTEXCOLOR");
            c.GetComponent<Renderer> ().enabled = false;
            c.AddComponent<Rigidbody> ();
            c.GetComponent<Rigidbody> ().mreplaced = 10;
            c.GetComponent<Rigidbody> ().Sleep ();
            c.GetComponent<Rigidbody> ().sleepThreshold = 1.0f;
            c.GetComponent<Rigidbody> ().angularDrag = 0.09f;
			c.GetComponent<Rigidbody> ().collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
            c.GetComponent<Renderer>().material.color = new Color32 (250, 200, 100, 255);
            freePool.Add(c);
        }
    }

19 Source : MapHandler.cs
with MIT License
from Lallassu

private void CreatePlane(float w, float h, float rotation, int x, int y) {
		GameObject plane = new GameObject("Plane");
		MeshFilter meshFilter = (MeshFilter)plane.AddComponent(typeof(MeshFilter));
		meshFilter.mesh = CreateMesh(w/2, h);
		MeshRenderer renderer = plane.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
		//renderer.material.shader = Shader.Find ("Particles/Additive");
		TextureHandler th = (TextureHandler)GameObject.FindObjectOfType<TextureHandler> ();
		//renderer.material.mainTexture = th.pillars;
		renderer.material.color = th.pillars;
		renderer.material.shader = Shader.Find ("Standard (Vertex Color)");
		//renderer.material.SetTextureScale("Tiling", new Vector2(5f,5f))
//		Texture2D tex = new Texture2D(1, 1);
//		tex.SetPixel(0, 0, Color.green);
//		tex.Apply();
//		renderer.material.mainTexture = tex;
//		renderer.material.color = Color.green;
		plane.transform.rotation = Quaternion.Euler(new Vector3(0,rotation,0));
		plane.transform.position = new Vector3 (x, -h+World.floorHeight-1, y);
	}

19 Source : ParadeMonitor.cs
with MIT License
from liangxiegame

void ComputeWaveform(RenderTexture source)
        {
            if (m_Buffer == null)
            {
                CreateBuffer(source.width, source.height);
            }
            else if (m_Buffer.count != (source.width * source.height))
            {
                m_Buffer.Release();
                CreateBuffer(source.width, source.height);
            }

            var channels = m_MonitorSettings.waveformY
                ? new Vector4(0f, 0f, 0f, 1f)
                : new Vector4(m_MonitorSettings.waveformR ? 1f : 0f, m_MonitorSettings.waveformG ? 1f : 0f, m_MonitorSettings.waveformB ? 1f : 0f, 0f);

            var cs = m_ComputeShader;

            int kernel = cs.FindKernel("KWaveformClear");
            cs.SetBuffer(kernel, "_Waveform", m_Buffer);
            cs.Dispatch(kernel, source.width, 1, 1);

            kernel = cs.FindKernel("KWaveform");
            cs.SetBuffer(kernel, "_Waveform", m_Buffer);
            cs.SetTexture(kernel, "_Source", source);
            cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
            cs.SetVector("_Channels", channels);
            cs.Dispatch(kernel, source.width, 1, 1);

            if (m_WaveformTexture == null || m_WaveformTexture.width != (source.width * 3) || m_WaveformTexture.height != source.height)
            {
                GraphicsUtils.Destroy(m_WaveformTexture);
                m_WaveformTexture = new RenderTexture(source.width * 3, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
                {
                    hideFlags = HideFlags.DontSave,
                    wrapMode = TextureWrapMode.Clamp,
                    filterMode = FilterMode.Bilinear
                };
            }

            if (m_Material == null)
                m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Parade Render")) { hideFlags = HideFlags.DontSave };

            m_Material.SetBuffer("_Waveform", m_Buffer);
            m_Material.SetVector("_Size", new Vector2(m_WaveformTexture.width, m_WaveformTexture.height));
            m_Material.SetVector("_Channels", channels);
        }

19 Source : WaveformMonitor.cs
with MIT License
from liangxiegame

void ComputeWaveform(RenderTexture source)
        {
            if (m_Buffer == null)
            {
                CreateBuffer(source.width, source.height);
            }
            else if (m_Buffer.count != (source.width * source.height))
            {
                m_Buffer.Release();
                CreateBuffer(source.width, source.height);
            }

            var channels = m_MonitorSettings.waveformY
                ? new Vector4(0f, 0f, 0f, 1f)
                : new Vector4(m_MonitorSettings.waveformR ? 1f : 0f, m_MonitorSettings.waveformG ? 1f : 0f, m_MonitorSettings.waveformB ? 1f : 0f, 0f);

            var cs = m_ComputeShader;

            int kernel = cs.FindKernel("KWaveformClear");
            cs.SetBuffer(kernel, "_Waveform", m_Buffer);
            cs.Dispatch(kernel, source.width, 1, 1);

            kernel = cs.FindKernel("KWaveform");
            cs.SetBuffer(kernel, "_Waveform", m_Buffer);
            cs.SetTexture(kernel, "_Source", source);
            cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
            cs.SetVector("_Channels", channels);
            cs.Dispatch(kernel, source.width, 1, 1);

            if (m_WaveformTexture == null || m_WaveformTexture.width != source.width || m_WaveformTexture.height != source.height)
            {
                GraphicsUtils.Destroy(m_WaveformTexture);
                m_WaveformTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
                {
                    hideFlags = HideFlags.DontSave,
                    wrapMode = TextureWrapMode.Clamp,
                    filterMode = FilterMode.Bilinear
                };
            }

            if (m_Material == null)
                m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Waveform Render")) { hideFlags = HideFlags.DontSave };

            m_Material.SetBuffer("_Waveform", m_Buffer);
            m_Material.SetVector("_Size", new Vector2(m_WaveformTexture.width, m_WaveformTexture.height));
            m_Material.SetVector("_Channels", channels);
        }

19 Source : ColorGradingModelEditor.cs
with MIT License
from liangxiegame

void DoCurvesGUI()
        {
            EditorGUILayout.Space();
            EditorGUI.indentLevel -= 2;
            ResetVisibleCurves();

            using (new EditorGUI.DisabledGroupScope(serializedProperty.serializedObject.isEditingMultipleObjects))
            {
                int curveEditingId = 0;

                // Top toolbar
                using (new GUILayout.HorizontalScope(EditorStyles.toolbar))
                {
                    curveEditingId = EditorGUILayout.Popup(m_Curves.currentEditingCurve.intValue, s_Curves, EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));
                    bool y = false, r = false, g = false, b = false;

                    if (curveEditingId == 0)
                    {
                        EditorGUILayout.Space();

                        bool rightClickedY, rightClickedR, rightClickedG, rightClickedB;

                        y = SpecialToggle(m_Curves.curveY.boolValue, "Y", out rightClickedY);
                        r = SpecialToggle(m_Curves.curveR.boolValue, "R", out rightClickedR);
                        g = SpecialToggle(m_Curves.curveG.boolValue, "G", out rightClickedG);
                        b = SpecialToggle(m_Curves.curveB.boolValue, "B", out rightClickedB);

                        if (!y && !r && !g && !b)
                        {
                            r = g = b = false;
                            y = true;
                        }

                        if (rightClickedY || rightClickedR || rightClickedG || rightClickedB)
                        {
                            y = rightClickedY;
                            r = rightClickedR;
                            g = rightClickedG;
                            b = rightClickedB;
                        }

                        if (y) SetCurveVisible(m_Curves.master);
                        if (r) SetCurveVisible(m_Curves.red);
                        if (g) SetCurveVisible(m_Curves.green);
                        if (b) SetCurveVisible(m_Curves.blue);

                        m_Curves.curveY.boolValue = y;
                        m_Curves.curveR.boolValue = r;
                        m_Curves.curveG.boolValue = g;
                        m_Curves.curveB.boolValue = b;
                    }
                    else
                    {
                        switch (curveEditingId)
                        {
                            case 1: SetCurveVisible(m_Curves.hueVShue);
                                break;
                            case 2: SetCurveVisible(m_Curves.hueVSsat);
                                break;
                            case 3: SetCurveVisible(m_Curves.satVSsat);
                                break;
                            case 4: SetCurveVisible(m_Curves.lumVSsat);
                                break;
                        }
                    }

                    GUILayout.FlexibleSpace();

                    if (GUILayout.Button("Reset", EditorStyles.toolbarButton))
                    {
                        switch (curveEditingId)
                        {
                            case 0:
                                if (y) m_Curves.master.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
                                if (r) m_Curves.red.animationCurveValue    = AnimationCurve.Linear(0f, 0f, 1f, 1f);
                                if (g) m_Curves.green.animationCurveValue  = AnimationCurve.Linear(0f, 0f, 1f, 1f);
                                if (b) m_Curves.blue.animationCurveValue   = AnimationCurve.Linear(0f, 0f, 1f, 1f);
                                break;
                            case 1: m_Curves.hueVShue.animationCurveValue = new AnimationCurve();
                                break;
                            case 2: m_Curves.hueVSsat.animationCurveValue = new AnimationCurve();
                                break;
                            case 3: m_Curves.satVSsat.animationCurveValue = new AnimationCurve();
                                break;
                            case 4: m_Curves.lumVSsat.animationCurveValue = new AnimationCurve();
                                break;
                        }
                    }

                    m_Curves.currentEditingCurve.intValue = curveEditingId;
                }

                // Curve area
                var settings = m_CurveEditor.settings;
                var rect = GUILayoutUtility.GetAspectRect(2f);
                var innerRect = settings.padding.Remove(rect);

                if (Event.current.type == EventType.Repaint)
                {
                    // Background
                    EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f));

                    if (s_MaterialSpline == null)
                        s_MaterialSpline = new Material(Shader.Find("Hidden/Post FX/UI/Curve Background")) { hideFlags = HideFlags.HideAndDontSave };

                    if (curveEditingId == 1 || curveEditingId == 2)
                        DrawBackgroundTexture(innerRect, 0);
                    else if (curveEditingId == 3 || curveEditingId == 4)
                        DrawBackgroundTexture(innerRect, 1);

                    // Bounds
                    Handles.color = Color.white;
                    Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f));

                    // Grid setup
                    Handles.color = new Color(1f, 1f, 1f, 0.05f);
                    int hLines = (int)Mathf.Sqrt(innerRect.width);
                    int vLines = (int)(hLines / (innerRect.width / innerRect.height));

                    // Vertical grid
                    int gridOffset = Mathf.FloorToInt(innerRect.width / hLines);
                    int gridPadding = ((int)(innerRect.width) % hLines) / 2;

                    for (int i = 1; i < hLines; i++)
                    {
                        var offset = i * Vector2.right * gridOffset;
                        offset.x += gridPadding;
                        Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset);
                    }

                    // Horizontal grid
                    gridOffset = Mathf.FloorToInt(innerRect.height / vLines);
                    gridPadding = ((int)(innerRect.height) % vLines) / 2;

                    for (int i = 1; i < vLines; i++)
                    {
                        var offset = i * Vector2.up * gridOffset;
                        offset.y += gridPadding;
                        Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset);
                    }
                }

                // Curve editor
                if (m_CurveEditor.OnGUI(rect))
                {
                    Repaint();
                    GUI.changed = true;
                }

                if (Event.current.type == EventType.Repaint)
                {
                    // Borders
                    Handles.color = Color.black;
                    Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f));
                    Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax));
                    Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax));
                    Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f));

                    // Selection info
                    var selection = m_CurveEditor.GetSelection();

                    if (selection.curve != null && selection.keyframeIndex > -1)
                    {
                        var key = selection.keyframe.Value;
                        var infoRect = innerRect;
                        infoRect.x += 5f;
                        infoRect.width = 100f;
                        infoRect.height = 30f;
                        GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), FxStyles.preLabel);
                    }
                }
            }

            /*
            EditorGUILayout.HelpBox(
                @"Curve editor cheat sheet:
- [Del] or [Backspace] to remove a key
- [Ctrl] to break a tangent handle
- [Shift] to align tangent handles
- [Double click] to create a key on the curve(s) at mouse position
- [Alt] + [Double click] to create a key on the curve(s) at a given time",
                MessageType.Info);
            */

            EditorGUILayout.Space();
            EditorGUI.indentLevel += 2;
        }

19 Source : HistogramMonitor.cs
with MIT License
from liangxiegame

void ComputeHistogram(RenderTexture source)
        {
            if (m_Buffer == null)
            {
                CreateBuffer(256, 1);
            }
            else if (m_Buffer.count != 256)
            {
                m_Buffer.Release();
                CreateBuffer(256, 1);
            }

            if (m_Material == null)
            {
                m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Histogram Render")) { hideFlags = HideFlags.DontSave };
            }

            var channels = Vector4.zero;
            switch (m_MonitorSettings.histogramMode)
            {
                case HistogramMode.Red: channels.x = 1f; break;
                case HistogramMode.Green: channels.y = 1f; break;
                case HistogramMode.Blue: channels.z = 1f; break;
                case HistogramMode.Luminance: channels.w = 1f; break;
                default: channels = new Vector4(1f, 1f, 1f, 0f); break;
            }

            var cs = m_ComputeShader;

            int kernel = cs.FindKernel("KHistogramClear");
            cs.SetBuffer(kernel, "_Histogram", m_Buffer);
            cs.Dispatch(kernel, 1, 1, 1);

            kernel = cs.FindKernel("KHistogramGather");
            cs.SetBuffer(kernel, "_Histogram", m_Buffer);
            cs.SetTexture(kernel, "_Source", source);
            cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
            cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
            cs.SetVector("_Channels", channels);
            cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 16f), Mathf.CeilToInt(source.height / 16f), 1);

            kernel = cs.FindKernel("KHistogramScale");
            cs.SetBuffer(kernel, "_Histogram", m_Buffer);
            cs.Dispatch(kernel, 1, 1, 1);

            if (m_HistogramTexture == null || m_HistogramTexture.width != source.width || m_HistogramTexture.height != source.height)
            {
                GraphicsUtils.Destroy(m_HistogramTexture);
                m_HistogramTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
                {
                    hideFlags = HideFlags.DontSave,
                    wrapMode = TextureWrapMode.Clamp,
                    filterMode = FilterMode.Bilinear
                };
            }

            m_Material.SetBuffer("_Histogram", m_Buffer);
            m_Material.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height));
            m_Material.SetColor("_ColorR", new Color(1f, 0f, 0f, 1f));
            m_Material.SetColor("_ColorG", new Color(0f, 1f, 0f, 1f));
            m_Material.SetColor("_ColorB", new Color(0f, 0f, 1f, 1f));
            m_Material.SetColor("_ColorL", new Color(1f, 1f, 1f, 1f));
            m_Material.SetInt("_Channel", (int)m_MonitorSettings.histogramMode);

            int preplaced = 0;
            if (m_MonitorSettings.histogramMode == HistogramMode.RGBMerged)
                preplaced = 1;
            else if (m_MonitorSettings.histogramMode == HistogramMode.RGBSplit)
                preplaced = 2;

            Graphics.Blit(null, m_HistogramTexture, m_Material, preplaced);
        }

19 Source : VectorscopeMonitor.cs
with MIT License
from liangxiegame

void ComputeVectorscope(RenderTexture source)
        {
            if (m_Buffer == null)
            {
                CreateBuffer(source.width, source.height);
            }
            else if (m_Buffer.count != (source.width * source.height))
            {
                m_Buffer.Release();
                CreateBuffer(source.width, source.height);
            }

            var cs = m_ComputeShader;

            int kernel = cs.FindKernel("KVectorscopeClear");
            cs.SetBuffer(kernel, "_Vectorscope", m_Buffer);
            cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
            cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1);

            kernel = cs.FindKernel("KVectorscope");
            cs.SetBuffer(kernel, "_Vectorscope", m_Buffer);
            cs.SetTexture(kernel, "_Source", source);
            cs.SetInt("_IsLinear", GraphicsUtils.isLinearColorSpace ? 1 : 0);
            cs.SetVector("_Res", new Vector4(source.width, source.height, 0f, 0f));
            cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1);

            if (m_VectorscopeTexture == null || m_VectorscopeTexture.width != source.width || m_VectorscopeTexture.height != source.height)
            {
                GraphicsUtils.Destroy(m_VectorscopeTexture);
                m_VectorscopeTexture = new RenderTexture(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear)
                {
                    hideFlags = HideFlags.DontSave,
                    wrapMode = TextureWrapMode.Clamp,
                    filterMode = FilterMode.Bilinear
                };
            }

            if (m_Material == null)
                m_Material = new Material(Shader.Find("Hidden/Post FX/Monitors/Vectorscope Render")) { hideFlags = HideFlags.DontSave };

            m_Material.SetBuffer("_Vectorscope", m_Buffer);
            m_Material.SetVector("_Size", new Vector2(m_VectorscopeTexture.width, m_VectorscopeTexture.height));
        }

19 Source : TrackballGroupDrawer.cs
with MIT License
from liangxiegame

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (s_Material == null)
                s_Material = new Material(Shader.Find("Hidden/Post FX/UI/Trackball")) { hideFlags = HideFlags.HideAndDontSave };

            position = new Rect(position.x, position.y, position.width / 3f, position.height);
            int size = m_Size;
            position.x += 5f;

            var enumerator = property.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var prop = enumerator.Current as SerializedProperty;
                if (prop == null || prop.propertyType != SerializedPropertyType.Color)
                    continue;

                OnWheelGUI(position, size, prop.Copy());
                position.x += position.width;
            }
        }

19 Source : MaterialFactory.cs
with MIT License
from liangxiegame

public Material Get(string shaderName)
        {
            Material material;

            if (!m_Materials.TryGetValue(shaderName, out material))
            {
                var shader = Shader.Find(shaderName);

                if (shader == null)
                    throw new ArgumentException(string.Format("Shader not found ({0})", shaderName));

                material = new Material(shader)
                {
                    name = string.Format("PostFX - {0}", shaderName.Substring(shaderName.LastIndexOf("/") + 1)),
                    hideFlags = HideFlags.DontSave
                };

                m_Materials.Add(shaderName, material);
            }

            return material;
        }

19 Source : GuideCtrl.cs
with MIT License
from liangxiegame

protected virtual void Awake()
		{
			//获取画布
			mCanvas = GameObject.FindObjectOfType<Canvas>();
			if (mCanvas == null)
			{
				Debug.LogError("There is not a Canvas!");
			}
			//材质初始化
			SetMatShader();
			mMaterial = new Material(Shader.Find(mShaderName));
			GetComponent<Image>().material = mMaterial;
			InitData();
		}

19 Source : MaterialHandler.cs
with GNU General Public License v3.0
from lmcintyre

private void LoadShaders()
	{
		if (shOverride)
		{
			standard = sh;
			nonBlend = sh;
			texBlend = sh;
			cutout = sh;
			cutoutWind = sh;
		}
		else
		{
			standard = Shader.Find("Standard");
			nonBlend = Shader.Find("Silent/FF14 World NonBlend");
			texBlend = Shader.Find("Silent/FF14 World TexBlend");
			cutout = Shader.Find("Silent/FF14 World Cutout");
			cutoutWind = Shader.Find("Silent/FF14 World Cutout (Multisampling + Wind)");	
		}
	}

19 Source : Render.cs
with MIT License
from MacSergey

public static Material CreateDecalMaterial(Texture2D texture, Texture2D aci = null, int renderQueue = 2460)
        {
            var material = new Material(Shader.Find("Custom/Props/Decal/Blend"))
            {
                mainTexture = texture,
                name = "NodeMarkupDecal",
                color = new Color(1f, 1f, 1f, 1f),
                doubleSidedGI = false,
                enableInstancing = false,
                globalIlluminationFlags = MaterialGlobalIlluminationFlags.EmissiveIsBlack,
                renderQueue = renderQueue,
            };
            if (aci != null)
                material.SetTexture("_ACIMap", aci);

            material.EnableKeyword("MULTI_INSTANCE");

            var tiling = new Vector4(1f, 0f, 1f, 0f);
            material.SetVector("_DecalTiling", tiling);

            return material;
        }

19 Source : Render.cs
with MIT License
from MacSergey

public static Material CreateRoadMaterial(Texture2D texture, Texture2D apr = null, int renderQueue = 2461)
        {
            var material = new Material(Shader.Find("Custom/Net/Road"))
            {
                mainTexture = texture,
                color = new Color(0.5f, 0.5f, 0.5f, 0),
                renderQueue = renderQueue,
            };

            if (apr != null)
                material.SetTexture("_APRMap", apr);

            //material.EnableKeyword("TERRAIN_SURFACE_ON");
            material.EnableKeyword("NET_SEGMENT");

            return material;
        }

19 Source : UIAtlasMaker.cs
with MIT License
from mamoniem

void OnGUI ()
	{
		if (mLastAtlas != NGUISettings.atlas)
			mLastAtlas = NGUISettings.atlas;

		bool update = false;
		bool replace = false;

		NGUIEditorTools.SetLabelWidth(84f);
		GUILayout.Space(3f);

		NGUIEditorTools.DrawHeader("Input", true);
		NGUIEditorTools.BeginContents(false);

		GUILayout.BeginHorizontal();
		{
			ComponentSelector.Draw<UIAtlas>("Atlas", NGUISettings.atlas, OnSelectAtlas, true, GUILayout.MinWidth(80f));

			EditorGUI.BeginDisabledGroup(NGUISettings.atlas == null);
			if (GUILayout.Button("New", GUILayout.Width(40f)))
				NGUISettings.atlas = null;
			EditorGUI.EndDisabledGroup();
		}
		GUILayout.EndHorizontal();

		List<Texture> textures = GetSelectedTextures();

		if (NGUISettings.atlas != null)
		{
			Material mat = NGUISettings.atlas.spriteMaterial;
			Texture tex = NGUISettings.atlas.texture;

			// Material information
			GUILayout.BeginHorizontal();
			{
				if (mat != null)
				{
					if (GUILayout.Button("Material", GUILayout.Width(76f))) Selection.activeObject = mat;
					GUILayout.Label(" " + mat.name);
				}
				else
				{
					GUI.color = Color.grey;
					GUILayout.Button("Material", GUILayout.Width(76f));
					GUI.color = Color.white;
					GUILayout.Label(" N/A");
				}
			}
			GUILayout.EndHorizontal();

			// Texture atlas information
			GUILayout.BeginHorizontal();
			{
				if (tex != null)
				{
					if (GUILayout.Button("Texture", GUILayout.Width(76f))) Selection.activeObject = tex;
					GUILayout.Label(" " + tex.width + "x" + tex.height);
				}
				else
				{
					GUI.color = Color.grey;
					GUILayout.Button("Texture", GUILayout.Width(76f));
					GUI.color = Color.white;
					GUILayout.Label(" N/A");
				}
			}
			GUILayout.EndHorizontal();
		}

		GUILayout.BeginHorizontal();
		NGUISettings.atlasPadding = Mathf.Clamp(EditorGUILayout.IntField("Padding", NGUISettings.atlasPadding, GUILayout.Width(100f)), 0, 8);
		GUILayout.Label((NGUISettings.atlasPadding == 1 ? "pixel" : "pixels") + " between sprites");
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		NGUISettings.atlasTrimming = EditorGUILayout.Toggle("Trim Alpha", NGUISettings.atlasTrimming, GUILayout.Width(100f));
		GUILayout.Label("Remove empty space");
		GUILayout.EndHorizontal();

		bool fixedShader = false;

		if (NGUISettings.atlas != null)
		{
			Material mat = NGUISettings.atlas.spriteMaterial;

			if (mat != null)
			{
				Shader shader = mat.shader;

				if (shader != null)
				{
					if (shader.name == "Unlit/Transparent Colored")
					{
						NGUISettings.atlasPMA = false;
						fixedShader = true;
					}
					else if (shader.name == "Unlit/Premultiplied Colored")
					{
						NGUISettings.atlasPMA = true;
						fixedShader = true;
					}
				}
			}
		}

		if (!fixedShader)
		{
			GUILayout.BeginHorizontal();
			NGUISettings.atlasPMA = EditorGUILayout.Toggle("PMA Shader", NGUISettings.atlasPMA, GUILayout.Width(100f));
			GUILayout.Label("Pre-multiplied alpha", GUILayout.MinWidth(70f));
			GUILayout.EndHorizontal();
		}

		//GUILayout.BeginHorizontal();
		//NGUISettings.keepPadding = EditorGUILayout.Toggle("Keep Padding", NGUISettings.keepPadding, GUILayout.Width(100f));
		//GUILayout.Label("or replace with trimmed pixels", GUILayout.MinWidth(70f));
		//GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		NGUISettings.unityPacking = EditorGUILayout.Toggle("Unity Packer", NGUISettings.unityPacking, GUILayout.Width(100f));
		GUILayout.Label("or custom packer", GUILayout.MinWidth(70f));
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		NGUISettings.trueColorAtlas = EditorGUILayout.Toggle("Truecolor", NGUISettings.trueColorAtlas, GUILayout.Width(100f));
		GUILayout.Label("force ARGB32 textures", GUILayout.MinWidth(70f));
		GUILayout.EndHorizontal();

		if (!NGUISettings.unityPacking)
		{
			GUILayout.BeginHorizontal();
			NGUISettings.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", NGUISettings.forceSquareAtlas, GUILayout.Width(100f));
			GUILayout.Label("if on, forces a square atlas texture", GUILayout.MinWidth(70f));
			GUILayout.EndHorizontal();
		}

#if UNITY_IPHONE || UNITY_ANDROID
		GUILayout.BeginHorizontal();
		NGUISettings.allow4096 = EditorGUILayout.Toggle("4096x4096", NGUISettings.allow4096, GUILayout.Width(100f));
		GUILayout.Label("if off, limit atlases to 2048x2048");
		GUILayout.EndHorizontal();
#endif
		NGUIEditorTools.EndContents();

		if (NGUISettings.atlas != null)
		{
			GUILayout.BeginHorizontal();
			GUILayout.Space(20f);

			if (textures.Count > 0)
			{
				update = GUILayout.Button("Add/Update");
			}
			else if (GUILayout.Button("View Sprites"))
			{
				SpriteSelector.ShowSelected();
			}

			GUILayout.Space(20f);
			GUILayout.EndHorizontal();
		}
		else
		{
			EditorGUILayout.HelpBox("You can create a new atlas by selecting one or more textures in the Project View window, then clicking \"Create\".", MessageType.Info);

			EditorGUI.BeginDisabledGroup(textures.Count == 0);
			GUILayout.BeginHorizontal();
			GUILayout.Space(20f);
			bool create = GUILayout.Button("Create");
			GUILayout.Space(20f);
			GUILayout.EndHorizontal();
			EditorGUI.EndDisabledGroup();

			if (create)
			{
				string path = EditorUtility.SaveFilePanelInProject("Save As",
					"New Atlas.prefab", "prefab", "Save atlas as...", NGUISettings.currentPath);

				if (!string.IsNullOrEmpty(path))
				{
					NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
					GameObject go = replacedetDatabase.LoadreplacedetAtPath(path, typeof(GameObject)) as GameObject;
					string matPath = path.Replace(".prefab", ".mat");
					replace = true;

					// Try to load the material
					Material mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;

					// If the material doesn't exist, create it
					if (mat == null)
					{
						Shader shader = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
						mat = new Material(shader);

						// Save the material
						replacedetDatabase.Createreplacedet(mat, matPath);
						replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

						// Load the material so it's usable
						mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;
					}

					// Create a new prefab for the atlas
					Object prefab = (go != null) ? go : PrefabUtility.CreateEmptyPrefab(path);

					// Create a new game object for the atlas
					string atlasName = path.Replace(".prefab", "");
					atlasName = atlasName.Substring(path.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
					go = new GameObject(atlasName);
					go.AddComponent<UIAtlas>().spriteMaterial = mat;

					// Update the prefab
					PrefabUtility.ReplacePrefab(go, prefab);
					DestroyImmediate(go);
					replacedetDatabase.Savereplacedets();
					replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

					// Select the atlas
					go = replacedetDatabase.LoadreplacedetAtPath(path, typeof(GameObject)) as GameObject;
					NGUISettings.atlas = go.GetComponent<UIAtlas>();
					Selection.activeGameObject = go;
				}
			}
		}

		string selection = null;
		Dictionary<string, int> spriteList = GetSpriteList(textures);

		if (spriteList.Count > 0)
		{
			NGUIEditorTools.DrawHeader("Sprites", true);
			{
				GUILayout.BeginHorizontal();
				GUILayout.Space(3f);
				GUILayout.BeginVertical();

				mScroll = GUILayout.BeginScrollView(mScroll);

				bool delete = false;
				int index = 0;
				foreach (KeyValuePair<string, int> iter in spriteList)
				{
					++index;

					GUILayout.Space(-1f);
					bool highlight = (UIAtlasInspector.instance != null) && (NGUISettings.selectedSprite == iter.Key);
					GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
					GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
					GUI.backgroundColor = Color.white;
					GUILayout.Label(index.ToString(), GUILayout.Width(24f));

					if (GUILayout.Button(iter.Key, "OL TextField", GUILayout.Height(20f)))
						selection = iter.Key;

					if (iter.Value == 2)
					{
						GUI.color = Color.green;
						GUILayout.Label("Add", GUILayout.Width(27f));
						GUI.color = Color.white;
					}
					else if (iter.Value == 1)
					{
						GUI.color = Color.cyan;
						GUILayout.Label("Update", GUILayout.Width(45f));
						GUI.color = Color.white;
					}
					else
					{
						if (mDelNames.Contains(iter.Key))
						{
							GUI.backgroundColor = Color.red;

							if (GUILayout.Button("Delete", GUILayout.Width(60f)))
							{
								delete = true;
							}
							GUI.backgroundColor = Color.green;
							if (GUILayout.Button("X", GUILayout.Width(22f)))
							{
								mDelNames.Remove(iter.Key);
								delete = false;
							}
							GUI.backgroundColor = Color.white;
						}
						else
						{
							// If we have not yet selected a sprite for deletion, show a small "X" button
							if (GUILayout.Button("X", GUILayout.Width(22f))) mDelNames.Add(iter.Key);
						}
					}
					GUILayout.EndHorizontal();
				}
				GUILayout.EndScrollView();
				GUILayout.EndVertical();
				GUILayout.Space(3f);
				GUILayout.EndHorizontal();

				// If this sprite was marked for deletion, remove it from the atlas
				if (delete)
				{
					List<SpriteEntry> sprites = new List<SpriteEntry>();
					ExtractSprites(NGUISettings.atlas, sprites);

					for (int i = sprites.Count; i > 0; )
					{
						SpriteEntry ent = sprites[--i];
						if (mDelNames.Contains(ent.name))
							sprites.RemoveAt(i);
					}
					UpdateAtlas(NGUISettings.atlas, sprites);
					mDelNames.Clear();
					NGUIEditorTools.RepaintSprites();
				}
				else if (update) UpdateAtlas(textures, true);
				else if (replace) UpdateAtlas(textures, false);

				if (NGUISettings.atlas != null && !string.IsNullOrEmpty(selection))
				{
					NGUIEditorTools.SelectSprite(selection);
				}
				else if (update || replace)
				{
					NGUIEditorTools.UpgradeTexturesToSprites(NGUISettings.atlas);
					NGUIEditorTools.RepaintSprites();
				}
			}
		}

		if (NGUISettings.atlas != null && textures.Count == 0)
			EditorGUILayout.HelpBox("You can reveal more options by selecting one or more textures in the Project View window.", MessageType.Info);

		// Uncomment this line if you want to be able to force-sort the atlas
		//if (NGUISettings.atlas != null && GUILayout.Button("Sort Alphabetically")) NGUISettings.atlas.SortAlphabetically();
	}

19 Source : UIFontMaker.cs
with MIT License
from mamoniem

void OnGUI ()
	{
		Object fnt = NGUISettings.ambigiousFont;
		UIFont uiFont = (fnt as UIFont);

		NGUIEditorTools.SetLabelWidth(80f);
		GUILayout.Space(3f);

		NGUIEditorTools.DrawHeader("Input", true);
		NGUIEditorTools.BeginContents(false);

		GUILayout.BeginHorizontal();
		mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f));
		NGUIEditorTools.DrawPadding();
		GUILayout.EndHorizontal();
		Create create = Create.None;

		if (mType == FontType.ImportedBitmap)
		{
			NGUISettings.fontData = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(Textreplacedet), false) as Textreplacedet;
			NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D;
			NGUIEditorTools.EndContents();

			// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
			EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
			{
				NGUIEditorTools.DrawHeader("Output", true);
				NGUIEditorTools.BeginContents(false);
				ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
				NGUIEditorTools.EndContents();
			}
			EditorGUI.EndDisabledGroup();

			if (NGUISettings.fontData == null)
			{
				EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " +
					"Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
					"Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
			}
			else if (NGUISettings.fontTexture == null)
			{
				EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info);
			}
			else if (NGUISettings.atlas == null)
			{
				EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
					"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
			}

			EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
			{
				GUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				if (GUILayout.Button("Create the Font")) create = Create.Import;
				GUILayout.Space(20f);
				GUILayout.EndHorizontal();
			}
			EditorGUI.EndDisabledGroup();
		}
		else
		{
			GUILayout.BeginHorizontal();
			if (NGUIEditorTools.DrawPrefixButton("Source"))
				ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });

			Font ttf = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont as Font, typeof(Font), false) as Font;
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			{
				NGUISettings.fontSize = EditorGUILayout.IntField("Size", NGUISettings.fontSize, GUILayout.Width(120f));

				if (mType == FontType.Dynamic)
				{
					NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle);
					NGUIEditorTools.DrawPadding();
				}
			}
			GUILayout.EndHorizontal();

			// Choose the font style if there are multiple faces present
			if (mType == FontType.GeneratedBitmap)
			{
				if (!FreeType.isPresent)
				{
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
					string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType.dll" : "FreeType.dylib";
#else
					string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType64.dll" : "FreeType64.dylib";
#endif
					EditorGUILayout.HelpBox("replacedets/NGUI/Editor/" + filename + " is missing", MessageType.Error);

					GUILayout.BeginHorizontal();
					GUILayout.Space(20f);

					if (GUILayout.Button("Find " + filename))
					{
						string path = EditorUtility.OpenFilePanel("Find " + filename, NGUISettings.currentPath,
							(Application.platform == RuntimePlatform.WindowsEditor) ? "dll" : "dylib");

						if (!string.IsNullOrEmpty(path))
						{
							if (System.IO.Path.GetFileName(path) == filename)
							{
								NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
								NGUISettings.pathToFreeType = path;
							}
							else Debug.LogError("The library must be named '" + filename + "'");
						}
					}
					GUILayout.Space(20f);
					GUILayout.EndHorizontal();
				}
				else if (ttf != null)
				{
					string[] faces = FreeType.GetFaces(ttf);

					if (faces != null)
					{
						if (mFaceIndex >= faces.Length) mFaceIndex = 0;

						if (faces.Length > 1)
						{
							GUILayout.Label("Style", EditorStyles.boldLabel);
							for (int i = 0; i < faces.Length; ++i)
							{
								GUILayout.BeginHorizontal();
								GUILayout.Space(10f);
								if (DrawOption(i == mFaceIndex, " " + faces[i]))
									mFaceIndex = i;
								GUILayout.EndHorizontal();
							}
						}
					}

					NGUISettings.fontKerning = EditorGUILayout.Toggle("Kerning", NGUISettings.fontKerning);

					GUILayout.Label("Characters", EditorStyles.boldLabel);

					CharacterMap cm = characterMap;

					GUILayout.BeginHorizontal(GUILayout.Width(100f));
					GUILayout.BeginVertical();
					GUI.changed = false;
					if (DrawOption(cm == CharacterMap.Numeric, " Numeric")) cm = CharacterMap.Numeric;
					if (DrawOption(cm == CharacterMap.Ascii, " ASCII")) cm = CharacterMap.Ascii;
					if (DrawOption(cm == CharacterMap.Latin, " Latin")) cm = CharacterMap.Latin;
					if (DrawOption(cm == CharacterMap.Custom, " Custom")) cm = CharacterMap.Custom;
					if (GUI.changed) characterMap = cm;
					GUILayout.EndVertical();

					EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom);
					{
						if (cm != CharacterMap.Custom)
						{
							string chars = "";

							if (cm == CharacterMap.Ascii)
							{
								for (int i = 33; i < 127; ++i)
									chars += System.Convert.ToChar(i);
							}
							else if (cm == CharacterMap.Numeric)
							{
								chars = "0123456789";
							}
							else if (cm == CharacterMap.Latin)
							{
								for (int i = 33; i < 127; ++i)
									chars += System.Convert.ToChar(i);

								for (int i = 161; i < 256; ++i)
									chars += System.Convert.ToChar(i);
							}

							NGUISettings.charsToInclude = chars;
						}

						GUI.changed = false;

						string text = NGUISettings.charsToInclude;

						if (cm == CharacterMap.Custom)
						{
							text = EditorGUILayout.TextArea(text, GUI.skin.textArea,
								GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
						}
						else
						{
							GUILayout.Label(text, GUI.skin.textArea,
								GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
						}

						if (GUI.changed)
						{
							string final = "";

							for (int i = 0; i < text.Length; ++i)
							{
								char c = text[i];
								if (c < 33) continue;
								string s = c.ToString();
								if (!final.Contains(s)) final += s;
							}

							if (final.Length > 0)
							{
								char[] chars = final.ToCharArray();
								System.Array.Sort(chars);
								final = new string(chars);
							}
							else final = "";

							NGUISettings.charsToInclude = final;
						}
					}
					EditorGUI.EndDisabledGroup();
					GUILayout.EndHorizontal();
				}
			}
			NGUIEditorTools.EndContents();

			if (mType == FontType.Dynamic)
			{
				EditorGUI.BeginDisabledGroup(ttf == null);
				GUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				if (GUILayout.Button("Create the Font")) create = Create.Dynamic;
				GUILayout.Space(20f);
				GUILayout.EndHorizontal();
				EditorGUI.EndDisabledGroup();
#if UNITY_3_5
				EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
				// Helpful info
				if (ttf == null)
				{
					EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info);
				}
				EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
			}
			else
			{
				bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.replacedetDatabase.GetreplacedetPath(ttf));

				// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
				EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent);
				{
					NGUIEditorTools.DrawHeader("Output", true);
					NGUIEditorTools.BeginContents(false);
					ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
					NGUIEditorTools.EndContents();

					if (ttf == null)
					{
						EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info);
					}
					else if (isBuiltIn)
					{
						EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning);
					}
					else if (NGUISettings.atlas == null)
					{
						EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
							"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
					}

					GUILayout.BeginHorizontal();
					GUILayout.Space(20f);
					if (GUILayout.Button("Create the Font")) create = Create.Bitmap;
					GUILayout.Space(20f);
					GUILayout.EndHorizontal();
				}
				EditorGUI.EndDisabledGroup();
			}
		}

		if (create == Create.None) return;

		// Open the "Save As" file dialog
#if UNITY_3_5
		string prefabPath = EditorUtility.SaveFilePanel("Save As",
			NGUISettings.currentPath, "New Font.prefab", "prefab");
#else
		string prefabPath = EditorUtility.SaveFilePanelInProject("Save As",
			"New Font.prefab", "prefab", "Save font as...", NGUISettings.currentPath);
#endif
		if (string.IsNullOrEmpty(prefabPath)) return;
		NGUISettings.currentPath = System.IO.Path.GetDirectoryName(prefabPath);

		// Load the font's prefab
		GameObject go = replacedetDatabase.LoadreplacedetAtPath(prefabPath, typeof(GameObject)) as GameObject;
		Object prefab = null;
		string fontName;

		// Font doesn't exist yet
		if (go == null || go.GetComponent<UIFont>() == null)
		{
			// Create a new prefab for the atlas
			prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);

			fontName = prefabPath.Replace(".prefab", "");
			fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);

			// Create a new game object for the font
			go = new GameObject(fontName);
			uiFont = go.AddComponent<UIFont>();
		}
		else
		{
			uiFont = go.GetComponent<UIFont>();
			fontName = go.name;
		}

		if (create == Create.Dynamic)
		{
			uiFont.atlas = null;
			uiFont.dynamicFont = NGUISettings.dynamicFont;
			uiFont.dynamicFontStyle = NGUISettings.fontStyle;
			uiFont.defaultSize = NGUISettings.fontSize;
		}
		else if (create == Create.Import)
		{
			Material mat = null;

			if (NGUISettings.atlas != null)
			{
				// Add the font's texture to the atlas
				UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
			}
			else
			{
				// Create a material for the font
				string matPath = prefabPath.Replace(".prefab", ".mat");
				mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;

				// If the material doesn't exist, create it
				if (mat == null)
				{
					Shader shader = Shader.Find("Unlit/Transparent Colored");
					mat = new Material(shader);

					// Save the material
					replacedetDatabase.Createreplacedet(mat, matPath);
					replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

					// Load the material so it's usable
					mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;
				}

				mat.mainTexture = NGUISettings.fontTexture;
			}

			uiFont.dynamicFont = null;
			BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes);

			if (NGUISettings.atlas == null)
			{
				uiFont.atlas = null;
				uiFont.material = mat;
			}
			else
			{
				uiFont.spriteName = NGUISettings.fontTexture.name;
				uiFont.atlas = NGUISettings.atlas;
			}
			NGUISettings.fontSize = uiFont.defaultSize;
		}
		else if (create == Create.Bitmap)
		{
			// Create the bitmap font
			BMFont bmFont;
			Texture2D tex;

			if (FreeType.CreateFont(
				NGUISettings.dynamicFont,
				NGUISettings.fontSize, mFaceIndex,
				NGUISettings.fontKerning,
				NGUISettings.charsToInclude, 1, out bmFont, out tex))
			{
				uiFont.bmFont = bmFont;
				tex.name = fontName;

				if (NGUISettings.atlas != null)
				{
					// Add this texture to the atlas and destroy it
					UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex);
					NGUITools.DestroyImmediate(tex);
					NGUISettings.fontTexture = null;
					tex = null;

					uiFont.atlas = NGUISettings.atlas;
					uiFont.spriteName = fontName;
				}
				else
				{
					string texPath = prefabPath.Replace(".prefab", ".png");
					string matPath = prefabPath.Replace(".prefab", ".mat");

					byte[] png = tex.EncodeToPNG();
					FileStream fs = File.OpenWrite(texPath);
					fs.Write(png, 0, png.Length);
					fs.Close();

					// See if the material already exists
					Material mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;

					// If the material doesn't exist, create it
					if (mat == null)
					{
						Shader shader = Shader.Find("Unlit/Transparent Colored");
						mat = new Material(shader);

						// Save the material
						replacedetDatabase.Createreplacedet(mat, matPath);
						replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

						// Load the material so it's usable
						mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;
					}
					else replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

					// Re-load the texture
					tex = replacedetDatabase.LoadreplacedetAtPath(texPath, typeof(Texture2D)) as Texture2D;

					// replacedign the texture
					mat.mainTexture = tex;
					NGUISettings.fontTexture = tex;

					uiFont.atlas = null;
					uiFont.material = mat;
				}
			}
			else return;
		}

		if (prefab != null)
		{
			// Update the prefab
			PrefabUtility.ReplacePrefab(go, prefab);
			DestroyImmediate(go);
			replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

			// Select the atlas
			go = replacedetDatabase.LoadreplacedetAtPath(prefabPath, typeof(GameObject)) as GameObject;
			uiFont = go.GetComponent<UIFont>();
		}

		if (uiFont != null) NGUISettings.ambigiousFont = uiFont;
		MarkAsChanged();
		Selection.activeGameObject = go;
	}

19 Source : UIDrawCall.cs
with MIT License
from mamoniem

void CreateMaterial ()
	{
		mTextureClip = false;
		mLegacyShader = false;
		mClipCount = panel.clipCount;

		string shaderName = (mShader != null) ? mShader.name :
			((mMaterial != null) ? mMaterial.shader.name : "Unlit/Transparent Colored");

		// Figure out the normal shader's name
		shaderName = shaderName.Replace("GUI/Text Shader", "Unlit/Text");

		if (shaderName.Length > 2)
		{
			if (shaderName[shaderName.Length - 2] == ' ')
			{
				int index = shaderName[shaderName.Length - 1];
				if (index > '0' && index <= '9') shaderName = shaderName.Substring(0, shaderName.Length - 2);
			}
		}

		if (shaderName.StartsWith("Hidden/"))
			shaderName = shaderName.Substring(7);

		// Legacy functionality
		const string soft = " (SoftClip)";
		shaderName = shaderName.Replace(soft, "");

		const string textureClip = " (TextureClip)";
		shaderName = shaderName.Replace(textureClip, "");

		if (panel.clipping == Clipping.TextureMask)
		{
			mTextureClip = true;
			shader = Shader.Find("Hidden/" + shaderName + textureClip);
		}
		else if (mClipCount != 0)
		{
			shader = Shader.Find("Hidden/" + shaderName + " " + mClipCount);
			if (shader == null) shader = Shader.Find(shaderName + " " + mClipCount);

			// Legacy functionality
			if (shader == null && mClipCount == 1)
			{
				mLegacyShader = true;
				shader = Shader.Find(shaderName + soft);
			}
		}
		else shader = Shader.Find(shaderName);

		// Always fallback to the default shader
		if (shader == null) shader = Shader.Find("Unlit/Transparent Colored");

		if (mMaterial != null)
		{
			mDynamicMat = new Material(mMaterial);
			mDynamicMat.name = "[NGUI] " + mMaterial.name;
			mDynamicMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
			mDynamicMat.CopyPropertiesFromMaterial(mMaterial);
#if !UNITY_FLASH
			string[] keywords = mMaterial.shaderKeywords;
			for (int i = 0; i < keywords.Length; ++i)
				mDynamicMat.EnableKeyword(keywords[i]);
#endif
			// If there is a valid shader, replacedign it to the custom material
			if (shader != null)
			{
				mDynamicMat.shader = shader;
			}
			else if (mClipCount != 0)
			{
				Debug.LogError(shaderName + " shader doesn't have a clipped shader version for " + mClipCount + " clip regions");
			}
		}
		else
		{
			mDynamicMat = new Material(shader);
			mDynamicMat.name = "[NGUI] " + shader.name;
			mDynamicMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
		}
	}

19 Source : UIAtlasMaker.cs
with Apache License 2.0
from OOXXXXOO

void OnGUI ()
	{
		if (mLastAtlas != NGUISettings.atlas)
			mLastAtlas = NGUISettings.atlas;

		bool update = false;
		bool replace = false;

		NGUIEditorTools.SetLabelWidth(80f);
		GUILayout.Space(3f);

		NGUIEditorTools.DrawHeader("Input", true);
		NGUIEditorTools.BeginContents(false);

		GUILayout.BeginHorizontal();
		{
			ComponentSelector.Draw<UIAtlas>("Atlas", NGUISettings.atlas, OnSelectAtlas, true, GUILayout.MinWidth(80f));

			EditorGUI.BeginDisabledGroup(NGUISettings.atlas == null);
			if (GUILayout.Button("New", GUILayout.Width(40f)))
				NGUISettings.atlas = null;
			EditorGUI.EndDisabledGroup();
		}
		GUILayout.EndHorizontal();

		List<Texture> textures = GetSelectedTextures();

		if (NGUISettings.atlas != null)
		{
			Material mat = NGUISettings.atlas.spriteMaterial;
			Texture tex = NGUISettings.atlas.texture;

			// Material information
			GUILayout.BeginHorizontal();
			{
				if (mat != null)
				{
					if (GUILayout.Button("Material", GUILayout.Width(76f))) Selection.activeObject = mat;
					GUILayout.Label(" " + mat.name);
				}
				else
				{
					GUI.color = Color.grey;
					GUILayout.Button("Material", GUILayout.Width(76f));
					GUI.color = Color.white;
					GUILayout.Label(" N/A");
				}
			}
			GUILayout.EndHorizontal();

			// Texture atlas information
			GUILayout.BeginHorizontal();
			{
				if (tex != null)
				{
					if (GUILayout.Button("Texture", GUILayout.Width(76f))) Selection.activeObject = tex;
					GUILayout.Label(" " + tex.width + "x" + tex.height);
				}
				else
				{
					GUI.color = Color.grey;
					GUILayout.Button("Texture", GUILayout.Width(76f));
					GUI.color = Color.white;
					GUILayout.Label(" N/A");
				}
			}
			GUILayout.EndHorizontal();
		}

		GUILayout.BeginHorizontal();
		NGUISettings.atlasPadding = Mathf.Clamp(EditorGUILayout.IntField("Padding", NGUISettings.atlasPadding, GUILayout.Width(100f)), 0, 8);
		GUILayout.Label((NGUISettings.atlasPadding == 1 ? "pixel" : "pixels") + " between sprites");
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		NGUISettings.atlasTrimming = EditorGUILayout.Toggle("Trim Alpha", NGUISettings.atlasTrimming, GUILayout.Width(100f));
		GUILayout.Label("Remove empty space");
		GUILayout.EndHorizontal();

		bool fixedShader = false;

		if (NGUISettings.atlas != null)
		{
			Material mat = NGUISettings.atlas.spriteMaterial;

			if (mat != null)
			{
				Shader shader = mat.shader;

				if (shader != null)
				{
					if (shader.name == "Unlit/Transparent Colored")
					{
						NGUISettings.atlasPMA = false;
						fixedShader = true;
					}
					else if (shader.name == "Unlit/Premultiplied Colored")
					{
						NGUISettings.atlasPMA = true;
						fixedShader = true;
					}
				}
			}
		}

		if (!fixedShader)
		{
			GUILayout.BeginHorizontal();
			NGUISettings.atlasPMA = EditorGUILayout.Toggle("PMA Shader", NGUISettings.atlasPMA, GUILayout.Width(100f));
			GUILayout.Label("Pre-multiplied alpha", GUILayout.MinWidth(70f));
			GUILayout.EndHorizontal();
		}

		GUILayout.BeginHorizontal();
		NGUISettings.unityPacking = EditorGUILayout.Toggle("Unity Packer", NGUISettings.unityPacking, GUILayout.Width(100f));
		GUILayout.Label("or custom packer", GUILayout.MinWidth(70f));
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		NGUISettings.trueColorAtlas = EditorGUILayout.Toggle("Truecolor", NGUISettings.trueColorAtlas, GUILayout.Width(100f));
		GUILayout.Label("force ARGB32 textures", GUILayout.MinWidth(70f));
		GUILayout.EndHorizontal();

		if (!NGUISettings.unityPacking)
		{
			GUILayout.BeginHorizontal();
			NGUISettings.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", NGUISettings.forceSquareAtlas, GUILayout.Width(100f));
			GUILayout.Label("if on, forces a square atlas texture", GUILayout.MinWidth(70f));
			GUILayout.EndHorizontal();
		}

#if UNITY_IPHONE || UNITY_ANDROID
		GUILayout.BeginHorizontal();
		NGUISettings.allow4096 = EditorGUILayout.Toggle("4096x4096", NGUISettings.allow4096, GUILayout.Width(100f));
		GUILayout.Label("if off, limit atlases to 2048x2048");
		GUILayout.EndHorizontal();
#endif
		NGUIEditorTools.EndContents();

		if (NGUISettings.atlas != null)
		{
			GUILayout.BeginHorizontal();
			GUILayout.Space(20f);

			if (textures.Count > 0)
			{
				update = GUILayout.Button("Add/Update");
			}
			else if (GUILayout.Button("View Sprites"))
			{
				SpriteSelector.ShowSelected();
			}

			GUILayout.Space(20f);
			GUILayout.EndHorizontal();
		}
		else
		{
			EditorGUILayout.HelpBox("You can create a new atlas by selecting one or more textures in the Project View window, then clicking \"Create\".", MessageType.Info);

			EditorGUI.BeginDisabledGroup(textures.Count == 0);
			GUILayout.BeginHorizontal();
			GUILayout.Space(20f);
			bool create = GUILayout.Button("Create");
			GUILayout.Space(20f);
			GUILayout.EndHorizontal();
			EditorGUI.EndDisabledGroup();

			if (create)
			{
				string path = EditorUtility.SaveFilePanelInProject("Save As",
					"New Atlas.prefab", "prefab", "Save atlas as...", NGUISettings.currentPath);

				if (!string.IsNullOrEmpty(path))
				{
					NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
					GameObject go = replacedetDatabase.LoadreplacedetAtPath(path, typeof(GameObject)) as GameObject;
					string matPath = path.Replace(".prefab", ".mat");
					replace = true;

					// Try to load the material
					Material mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;

					// If the material doesn't exist, create it
					if (mat == null)
					{
						Shader shader = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
						mat = new Material(shader);

						// Save the material
						replacedetDatabase.Createreplacedet(mat, matPath);
						replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

						// Load the material so it's usable
						mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;
					}

					// Create a new prefab for the atlas
					Object prefab = (go != null) ? go : PrefabUtility.CreateEmptyPrefab(path);

					// Create a new game object for the atlas
					string atlasName = path.Replace(".prefab", "");
					atlasName = atlasName.Substring(path.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
					go = new GameObject(atlasName);
					go.AddComponent<UIAtlas>().spriteMaterial = mat;

					// Update the prefab
					PrefabUtility.ReplacePrefab(go, prefab);
					DestroyImmediate(go);
					replacedetDatabase.Savereplacedets();
					replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

					// Select the atlas
					go = replacedetDatabase.LoadreplacedetAtPath(path, typeof(GameObject)) as GameObject;
					NGUISettings.atlas = go.GetComponent<UIAtlas>();
					Selection.activeGameObject = go;
				}
			}
		}

		string selection = null;
		Dictionary<string, int> spriteList = GetSpriteList(textures);

		if (spriteList.Count > 0)
		{
			NGUIEditorTools.DrawHeader("Sprites", true);
			{
				GUILayout.BeginHorizontal();
				GUILayout.Space(3f);
				GUILayout.BeginVertical();

				mScroll = GUILayout.BeginScrollView(mScroll);

				bool delete = false;
				int index = 0;
				foreach (KeyValuePair<string, int> iter in spriteList)
				{
					++index;

					GUILayout.Space(-1f);
					bool highlight = (UIAtlasInspector.instance != null) && (NGUISettings.selectedSprite == iter.Key);
					GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
					GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
					GUI.backgroundColor = Color.white;
					GUILayout.Label(index.ToString(), GUILayout.Width(24f));

					if (GUILayout.Button(iter.Key, "OL TextField", GUILayout.Height(20f)))
						selection = iter.Key;

					if (iter.Value == 2)
					{
						GUI.color = Color.green;
						GUILayout.Label("Add", GUILayout.Width(27f));
						GUI.color = Color.white;
					}
					else if (iter.Value == 1)
					{
						GUI.color = Color.cyan;
						GUILayout.Label("Update", GUILayout.Width(45f));
						GUI.color = Color.white;
					}
					else
					{
						if (mDelNames.Contains(iter.Key))
						{
							GUI.backgroundColor = Color.red;

							if (GUILayout.Button("Delete", GUILayout.Width(60f)))
							{
								delete = true;
							}
							GUI.backgroundColor = Color.green;
							if (GUILayout.Button("X", GUILayout.Width(22f)))
							{
								mDelNames.Remove(iter.Key);
								delete = false;
							}
							GUI.backgroundColor = Color.white;
						}
						else
						{
							// If we have not yet selected a sprite for deletion, show a small "X" button
							if (GUILayout.Button("X", GUILayout.Width(22f))) mDelNames.Add(iter.Key);
						}
					}
					GUILayout.EndHorizontal();
				}
				GUILayout.EndScrollView();
				GUILayout.EndVertical();
				GUILayout.Space(3f);
				GUILayout.EndHorizontal();

				// If this sprite was marked for deletion, remove it from the atlas
				if (delete)
				{
					List<SpriteEntry> sprites = new List<SpriteEntry>();
					ExtractSprites(NGUISettings.atlas, sprites);

					for (int i = sprites.Count; i > 0; )
					{
						SpriteEntry ent = sprites[--i];
						if (mDelNames.Contains(ent.name))
							sprites.RemoveAt(i);
					}
					UpdateAtlas(NGUISettings.atlas, sprites);
					mDelNames.Clear();
					NGUIEditorTools.RepaintSprites();
				}
				else if (update) UpdateAtlas(textures, true);
				else if (replace) UpdateAtlas(textures, false);

				if (NGUISettings.atlas != null && !string.IsNullOrEmpty(selection))
				{
					NGUIEditorTools.SelectSprite(selection);
				}
				else if (update || replace)
				{
					NGUIEditorTools.UpgradeTexturesToSprites(NGUISettings.atlas);
					NGUIEditorTools.RepaintSprites();
				}
			}
		}

		if (NGUISettings.atlas != null && textures.Count == 0)
			EditorGUILayout.HelpBox("You can reveal more options by selecting one or more textures in the Project View window.", MessageType.Info);

		// Uncomment this line if you want to be able to force-sort the atlas
		//if (NGUISettings.atlas != null && GUILayout.Button("Sort Alphabetically")) NGUISettings.atlas.SortAlphabetically();
	}

19 Source : UIFontMaker.cs
with Apache License 2.0
from OOXXXXOO

void OnGUI ()
	{
		Object fnt = NGUISettings.ambigiousFont;
		UIFont uiFont = (fnt as UIFont);

		NGUIEditorTools.SetLabelWidth(80f);
		GUILayout.Space(3f);

		NGUIEditorTools.DrawHeader("Input", true);
		NGUIEditorTools.BeginContents(false);

		GUILayout.BeginHorizontal();
		mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f));
		NGUIEditorTools.DrawPadding();
		GUILayout.EndHorizontal();
		Create create = Create.None;

		if (mType == FontType.ImportedBitmap)
		{
			NGUISettings.fontData = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(Textreplacedet), false) as Textreplacedet;
			NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D;
			NGUIEditorTools.EndContents();

			// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
			EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
			{
				NGUIEditorTools.DrawHeader("Output", true);
				NGUIEditorTools.BeginContents(false);
				ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
				NGUIEditorTools.EndContents();
			}
			EditorGUI.EndDisabledGroup();

			if (NGUISettings.fontData == null)
			{
				EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " +
					"Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
					"Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
			}
			else if (NGUISettings.fontTexture == null)
			{
				EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info);
			}
			else if (NGUISettings.atlas == null)
			{
				EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
					"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
			}

			EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
			{
				GUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				if (GUILayout.Button("Create the Font")) create = Create.Import;
				GUILayout.Space(20f);
				GUILayout.EndHorizontal();
			}
			EditorGUI.EndDisabledGroup();
		}
		else
		{
			GUILayout.BeginHorizontal();
			if (NGUIEditorTools.DrawPrefixButton("Source"))
				ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });

			Font ttf = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont as Font, typeof(Font), false) as Font;
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			{
				NGUISettings.fontSize = EditorGUILayout.IntField("Size", NGUISettings.fontSize, GUILayout.Width(120f));

				if (mType == FontType.Dynamic)
				{
					NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle);
					NGUIEditorTools.DrawPadding();
				}
			}
			GUILayout.EndHorizontal();

			// Choose the font style if there are multiple faces present
			if (mType == FontType.GeneratedBitmap)
			{
				if (!FreeType.isPresent)
				{
					string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType.dll" : "FreeType.dylib";
					
					EditorGUILayout.HelpBox("replacedets/NGUI/Editor/" + filename + " is missing", MessageType.Error);

					GUILayout.BeginHorizontal();
					GUILayout.Space(20f);

					if (GUILayout.Button("Find " + filename))
					{
						string path = EditorUtility.OpenFilePanel("Find " + filename, NGUISettings.currentPath,
							(Application.platform == RuntimePlatform.WindowsEditor) ? "dll" : "dylib");

						if (!string.IsNullOrEmpty(path))
						{
							if (System.IO.Path.GetFileName(path) == filename)
							{
								NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
								NGUISettings.pathToFreeType = path;
							}
							else Debug.LogError("The library must be named '" + filename + "'");
						}
					}
					GUILayout.Space(20f);
					GUILayout.EndHorizontal();
				}
				else if (ttf != null)
				{
					string[] faces = FreeType.GetFaces(ttf);

					if (faces != null)
					{
						if (mFaceIndex >= faces.Length) mFaceIndex = 0;

						if (faces.Length > 1)
						{
							GUILayout.Label("Style", EditorStyles.boldLabel);
							for (int i = 0; i < faces.Length; ++i)
							{
								GUILayout.BeginHorizontal();
								GUILayout.Space(10f);
								if (DrawOption(i == mFaceIndex, " " + faces[i]))
									mFaceIndex = i;
								GUILayout.EndHorizontal();
							}
						}
					}

					GUILayout.Label("Characters", EditorStyles.boldLabel);

					CharacterMap cm = characterMap;

					GUILayout.BeginHorizontal(GUILayout.Width(100f));
					GUILayout.BeginVertical();
					GUI.changed = false;
					if (DrawOption(cm == CharacterMap.Numeric, " Numeric")) cm = CharacterMap.Numeric;
					if (DrawOption(cm == CharacterMap.Ascii, " ASCII")) cm = CharacterMap.Ascii;
					if (DrawOption(cm == CharacterMap.Latin, " Latin")) cm = CharacterMap.Latin;
					if (DrawOption(cm == CharacterMap.Custom, " Custom")) cm = CharacterMap.Custom;
					if (GUI.changed) characterMap = cm;
					GUILayout.EndVertical();

					EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom);
					{
						if (cm != CharacterMap.Custom)
						{
							string chars = "";

							if (cm == CharacterMap.Ascii)
							{
								for (int i = 33; i < 127; ++i)
									chars += System.Convert.ToChar(i);
							}
							else if (cm == CharacterMap.Numeric)
							{
								chars = "01234567890";
							}
							else if (cm == CharacterMap.Latin)
							{
								for (int i = 33; i < 127; ++i)
									chars += System.Convert.ToChar(i);

								for (int i = 161; i < 256; ++i)
									chars += System.Convert.ToChar(i);
							}

							NGUISettings.charsToInclude = chars;
						}

						GUI.changed = false;

						string text = NGUISettings.charsToInclude;

						if (cm == CharacterMap.Custom)
						{
							text = EditorGUILayout.TextArea(text, GUI.skin.textArea,
								GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
						}
						else
						{
							GUILayout.Label(text, GUI.skin.textArea,
								GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
						}

						if (GUI.changed)
						{
							string final = "";

							for (int i = 0; i < text.Length; ++i)
							{
								char c = text[i];
								if (c < 33) continue;
								string s = c.ToString();
								if (!final.Contains(s)) final += s;
							}

							if (final.Length > 0)
							{
								char[] chars = final.ToCharArray();
								System.Array.Sort(chars);
								final = new string(chars);
							}
							else final = "";

							NGUISettings.charsToInclude = final;
						}
					}
					EditorGUI.EndDisabledGroup();
					GUILayout.EndHorizontal();
				}
			}
			NGUIEditorTools.EndContents();

			if (mType == FontType.Dynamic)
			{
				EditorGUI.BeginDisabledGroup(ttf == null);
				GUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				if (GUILayout.Button("Create the Font")) create = Create.Dynamic;
				GUILayout.Space(20f);
				GUILayout.EndHorizontal();
				EditorGUI.EndDisabledGroup();
#if UNITY_3_5
				EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
				// Helpful info
				if (ttf == null)
				{
					EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info);
				}
				EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
			}
			else
			{
				bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.replacedetDatabase.GetreplacedetPath(ttf));

				// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
				EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent);
				{
					NGUIEditorTools.DrawHeader("Output", true);
					NGUIEditorTools.BeginContents(false);
					ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
					NGUIEditorTools.EndContents();

					if (ttf == null)
					{
						EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info);
					}
					else if (isBuiltIn)
					{
						EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning);
					}
					else if (NGUISettings.atlas == null)
					{
						EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
							"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
					}

					GUILayout.BeginHorizontal();
					GUILayout.Space(20f);
					if (GUILayout.Button("Create the Font")) create = Create.Bitmap;
					GUILayout.Space(20f);
					GUILayout.EndHorizontal();
				}
				EditorGUI.EndDisabledGroup();
			}
		}

		if (create == Create.None) return;

		// Open the "Save As" file dialog
#if UNITY_3_5
		string prefabPath = EditorUtility.SaveFilePanel("Save As",
			NGUISettings.currentPath, "New Font.prefab", "prefab");
#else
		string prefabPath = EditorUtility.SaveFilePanelInProject("Save As",
			"New Font.prefab", "prefab", "Save font as...", NGUISettings.currentPath);
#endif
		if (string.IsNullOrEmpty(prefabPath)) return;
		NGUISettings.currentPath = System.IO.Path.GetDirectoryName(prefabPath);

		// Load the font's prefab
		GameObject go = replacedetDatabase.LoadreplacedetAtPath(prefabPath, typeof(GameObject)) as GameObject;
		Object prefab = null;
		string fontName;

		// Font doesn't exist yet
		if (go == null || go.GetComponent<UIFont>() == null)
		{
			// Create a new prefab for the atlas
			prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);

			fontName = prefabPath.Replace(".prefab", "");
			fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);

			// Create a new game object for the font
			go = new GameObject(fontName);
			uiFont = go.AddComponent<UIFont>();
		}
		else
		{
			uiFont = go.GetComponent<UIFont>();
			fontName = go.name;
		}

		if (create == Create.Dynamic)
		{
			uiFont.atlas = null;
			uiFont.dynamicFont = NGUISettings.dynamicFont;
			uiFont.dynamicFontStyle = NGUISettings.fontStyle;
			uiFont.defaultSize = NGUISettings.fontSize;
		}
		else if (create == Create.Import)
		{
			Material mat = null;

			if (NGUISettings.atlas != null)
			{
				// Add the font's texture to the atlas
				UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
			}
			else
			{
				// Create a material for the font
				string matPath = prefabPath.Replace(".prefab", ".mat");
				mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;

				// If the material doesn't exist, create it
				if (mat == null)
				{
					Shader shader = Shader.Find("Unlit/Transparent Colored");
					mat = new Material(shader);

					// Save the material
					replacedetDatabase.Createreplacedet(mat, matPath);
					replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

					// Load the material so it's usable
					mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;
				}

				mat.mainTexture = NGUISettings.fontTexture;
			}

			uiFont.dynamicFont = null;
			BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes);

			if (NGUISettings.atlas == null)
			{
				uiFont.atlas = null;
				uiFont.material = mat;
			}
			else
			{
				uiFont.spriteName = NGUISettings.fontTexture.name;
				uiFont.atlas = NGUISettings.atlas;
			}
			NGUISettings.fontSize = uiFont.defaultSize;
		}
		else if (create == Create.Bitmap)
		{
			// Create the bitmap font
			BMFont bmFont;
			Texture2D tex;

			if (FreeType.CreateFont(
				NGUISettings.dynamicFont,
				NGUISettings.fontSize, mFaceIndex,
				NGUISettings.charsToInclude, out bmFont, out tex))
			{
				uiFont.bmFont = bmFont;
				tex.name = fontName;

				if (NGUISettings.atlas != null)
				{
					// Add this texture to the atlas and destroy it
					UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex);
					NGUITools.DestroyImmediate(tex);
					NGUISettings.fontTexture = null;
					tex = null;

					uiFont.atlas = NGUISettings.atlas;
					uiFont.spriteName = fontName;
				}
				else
				{
					string texPath = prefabPath.Replace(".prefab", ".png");
					string matPath = prefabPath.Replace(".prefab", ".mat");

					byte[] png = tex.EncodeToPNG();
					FileStream fs = File.OpenWrite(texPath);
					fs.Write(png, 0, png.Length);
					fs.Close();

					// See if the material already exists
					Material mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;

					// If the material doesn't exist, create it
					if (mat == null)
					{
						Shader shader = Shader.Find("Unlit/Transparent Colored");
						mat = new Material(shader);

						// Save the material
						replacedetDatabase.Createreplacedet(mat, matPath);
						replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

						// Load the material so it's usable
						mat = replacedetDatabase.LoadreplacedetAtPath(matPath, typeof(Material)) as Material;
					}
					else replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

					// Re-load the texture
					tex = replacedetDatabase.LoadreplacedetAtPath(texPath, typeof(Texture2D)) as Texture2D;

					// replacedign the texture
					mat.mainTexture = tex;
					NGUISettings.fontTexture = tex;

					uiFont.atlas = null;
					uiFont.material = mat;
				}
			}
			else return;
		}

		if (prefab != null)
		{
			// Update the prefab
			PrefabUtility.ReplacePrefab(go, prefab);
			DestroyImmediate(go);
			replacedetDatabase.Refresh(ImportreplacedetOptions.ForceSynchronousImport);

			// Select the atlas
			go = replacedetDatabase.LoadreplacedetAtPath(prefabPath, typeof(GameObject)) as GameObject;
			uiFont = go.GetComponent<UIFont>();
		}

		if (uiFont != null) NGUISettings.ambigiousFont = uiFont;
		MarkAsChanged();
		Selection.activeGameObject = go;
	}

19 Source : UIDrawCall.cs
with Apache License 2.0
from OOXXXXOO

void CreateMaterial ()
	{
		mLegacyShader = false;
		mClipCount = panel.clipCount;

		string shaderName = (mShader != null) ? mShader.name :
			((mMaterial != null) ? mMaterial.shader.name : "Unlit/Transparent Colored");

		// Figure out the normal shader's name
		shaderName = shaderName.Replace("GUI/Text Shader", "Unlit/Text");

		if (shaderName.Length > 2)
		{
			if (shaderName[shaderName.Length - 2] == ' ')
			{
				int index = shaderName[shaderName.Length - 1];
				if (index > '0' && index <= '9') shaderName = shaderName.Substring(0, shaderName.Length - 2);
			}
		}

		if (shaderName.StartsWith("Hidden/"))
			shaderName = shaderName.Substring(7);

		// Legacy functionality
		const string soft = " (SoftClip)";
		shaderName = shaderName.Replace(soft, "");

		if (mClipCount != 0)
		{
			shader = Shader.Find("Hidden/" + shaderName + " " + mClipCount);
			if (shader == null) Shader.Find(shaderName + " " + mClipCount);

			// Legacy functionality
			if (shader == null && mClipCount == 1)
			{
				mLegacyShader = true;
				shader = Shader.Find(shaderName + soft);
			}
		}
		else shader = Shader.Find(shaderName);

		if (mMaterial != null)
		{
			mDynamicMat = new Material(mMaterial);
			mDynamicMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
			mDynamicMat.CopyPropertiesFromMaterial(mMaterial);
#if !UNITY_FLASH
			string[] keywords = mMaterial.shaderKeywords;
			for (int i = 0; i < keywords.Length; ++i)
				mDynamicMat.EnableKeyword(keywords[i]);
#endif
			// If there is a valid shader, replacedign it to the custom material
			if (shader != null)
			{
				mDynamicMat.shader = shader;
			}
			else if (mClipCount != 0)
			{
				Debug.LogError(shaderName + " shader doesn't have a clipped shader version for " + mClipCount + " clip regions");
			}
		}
		else
		{
			mDynamicMat = new Material(shader);
			mDynamicMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
		}
	}

19 Source : xAxisRotate.cs
with MIT License
from pampas93

void Start () {

        defaultShader = this.GetComponent<Renderer>().material.shader;
        x = Shader.Find("Legacy Shaders/Self-Illumin/Bumped Diffuse");
        GameObject grandParent = this.gameObject.transform.parent.gameObject.transform.parent.gameObject;
        //Debug.Log(grandParent);
        rotateScript = grandParent.GetComponent<HandRotate>();

    }

19 Source : yAxisRotate.cs
with MIT License
from pampas93

void Start()
    {

        defaultShader = this.GetComponent<Renderer>().material.shader;
        x = Shader.Find("Legacy Shaders/Self-Illumin/Bumped Diffuse");
        GameObject grandParent = this.gameObject.transform.parent.gameObject.transform.parent.gameObject;
        //Debug.Log(grandParent);
        rotateScript = grandParent.GetComponent<HandRotate>();

    }

See More Examples