Monday, 14 January 2019

Unity C# 3D Progress bar - Creating a Progress bar which scales over time

1. Create a progress bar with outer frame(fixed) and a inner slider (scales over time) something as shown in the below pic.
2. Attach the below script to an empty game object and drag the slider game object on to the progress slider



using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProgressBar : MonoBehaviour
{
    public GameObject progressSlider;
    float totalWidth;
    float totalDuration = 100.0f;
    float currentTime;
    float currentWidth;


// Use this for initialization
void Start ()
    {
        totalWidth = progressSlider.transform.localScale.x;
        currentWidth = totalWidth / 100;
        progressSlider.transform.localScale = new Vector3(currentWidth, progressSlider.transform.localScale.y, progressSlider.transform.localScale.z);


    }

// Update is called once per frame
void Update ()
    {
        currentTime += Time.deltaTime;
        if(currentTime<totalDuration )
        {
            if(currentWidth <= totalWidth)
            {
                currentWidth += 0.01f;
                progressSlider.transform.localScale = new Vector3(currentWidth, progressSlider.transform.localScale.y, progressSlider.transform.localScale.z);
            }
           
        }


    }
}


That's it run the scene.

Creating a Dictation Recognizer in Unity C# - Hololens

1.Create a new scene and apply the mixed reality scene settings.
2. Create a UI text component and drag on to the inputtext field on the next step after attaching the code.
2. Create a new button and attach the below script and trigger the InitateRecording function on click event


using UnityEditor;

using UnityEngine.UI;
using UnityEngine;
using HoloToolkit.Unity.InputModule;
using UnityEngine.Windows.Speech;

public class DictationHandler : MonoBehaviour {

   
    public GameObject inputtext = null, icon = null;
    public Material recording = null, stopped = null;
 
         [SerializeField]
    private Text m_Hypotheses;

    [SerializeField]
    private Text m_Recognitions;

    private DictationRecognizer m_DictationRecognizer;

    bool isRecording;

    public void InitateRecording()
    {
        if(!isRecording)
        {
            isRecording = true;
            StartRecording();
        }
        else
        {
            isRecording = false;
            StopRecording();
        }
    }

     void StartRecording()
    {
        icon.GetComponent<MeshRenderer>().material = recording;
        m_DictationRecognizer = new DictationRecognizer();

        m_DictationRecognizer.DictationResult += (text, confidence) =>
        {
            Debug.LogFormat("Dictation result: {0}", text);
            inputtext.GetComponent<UnityEngine.UI.Text>().text += text ;
        };

        m_DictationRecognizer.DictationHypothesis += (text) =>
        {
            Debug.LogFormat("Dictation hypothesis: {0}", text);
            m_Hypotheses.text += text;
        };

        m_DictationRecognizer.DictationComplete += (completionCause) =>
        {
            if (completionCause != DictationCompletionCause.Complete)
                Debug.LogErrorFormat("Dictation completed unsuccessfully: {0}.", completionCause);
        };

        m_DictationRecognizer.DictationError += (error, hresult) =>
        {
            Debug.LogErrorFormat("Dictation error: {0}; HResult = {1}.", error, hresult);
        };

        m_DictationRecognizer.Start();
    }
     void StopRecording()
    {
        m_DictationRecognizer.Stop();
        icon.GetComponent<MeshRenderer>().material = stopped;
    }

    }

Thursday, 29 November 2018

Getting Timestamp in Unity C#

Create two 3DText mesh in unity and create a empty game object and attach the below script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeStampHandler : MonoBehaviour
{
    public TextMesh dateText, timeText;

    // Use this for initialization
    void Start () {

}

    void Update()
    {
        //string currDay = System.DayOfWeek;
        string currDate = System.DateTime.Now.ToString("yyyy/MM/dd ").ToString();
        string currTime = System.DateTime.Now.ToString("HH:mm:ss").ToString();
        dateText.text = System.DateTime.Now.DayOfWeek.ToString() + " " + currDate;
        timeText.text = currTime;
    }
}

Tuesday, 13 November 2018

Atmosphere Shader in Unity

Shader "Custom/Atmosphere" {
Properties{
_Color("Color", Color) = (1,1,1,1)
_Size("Atmosphere Size Multiplier", Range(0,16)) = 4
_Rim("Fade Power", Range(0,8)) = 4
_Light("Lighting Power", Range(0,10)) = 1.4
_Ambient("Ambient Power", Range(0,6)) = 0.8

}
SubShader{
Tags{ "RenderType" = "Transparent" }
LOD 200

Cull Front

CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf NegativeLambert fullforwardshadows alpha:fade
#pragma vertex vert

// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0


struct Input {
float3 viewDir;
};

half _Size;
half _Rim;
half _Light;
half _Ambient;
fixed4 _Color;

void vert(inout appdata_full v) {
v.vertex.xyz += v.vertex.xyz * _Size / 10;
v.normal *= -1;
}

half4 LightingNegativeLambert(SurfaceOutput s, half3 lightDir, half3 viewDir, half atten) {
s.Normal = normalize(s.Normal);

half diff = max(0, dot(-s.Normal, lightDir)) * _Light + _Ambient;

half4 c;
c.rgb = (s.Albedo * _LightColor0 * diff) * atten;
c.a = s.Alpha;
return c;
}

void surf(Input IN, inout SurfaceOutput o) {
half rim = saturate(dot(normalize(IN.viewDir), o.Normal));

// Albedo comes from a texture tinted by color
fixed4 c = _Color;
o.Albedo = c.rgb;
o.Alpha = lerp(0, 1, pow(rim, _Rim));
}
ENDCG
}
FallBack "Diffuse"
}

Monday, 12 November 2018

Gradient Shader in Unity

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/gradient" {
Properties
{
_TopColor("Top Color", Color) = (1, 1, 1, 1)
_BottomColor("Bottom Color", Color) = (1, 1, 1, 1)
_RampTex("Ramp Texture", 2D) = "white" {}
}
SubShader
{
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct vertexIn {
float4 pos : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert(vertexIn input)
{
v2f output;
output.pos = UnityObjectToClipPos(input.pos);
output.uv = input.uv;
return output;
}
fixed4 _TopColor, _BottomColor;
sampler2D _RampTex;
fixed4 frag(v2f input) : COLOR
{
return lerp(_BottomColor, _TopColor, input.uv.x);
}
ENDCG
}
}
}

Back Face Culling shader in Unity

Shader "Custom/backFaceChecker" {
Properties{
_Color("Main Color", Color) = (1,1,1,1)
_SpecColor("Specular Color", Color) = (0.5, 0.5, 0.5, 0)
_Shininess("Shininess", Range(0.01, 1)) = 0.078125
_MainTex("Base (RGB) TransGloss (A)", 2D) = "white" {}
_BumpMap("Normalmap", 2D) = "bump" {}
_Cutoff("Alpha cutoff", Range(0,1)) = 0.5
}

SubShader{
Cull Off
Tags{ "Queue" = "AlphaTest" "IgnoreProjector" = "True" "RenderType" = "TransparentCutout" }
LOD 400

CGPROGRAM
#pragma surface surf BlinnPhong alphatest:_Cutoff
#pragma exclude_renderers flash

sampler2D _MainTex;
sampler2D _BumpMap;
fixed4 _Color;
half _Shininess;

struct Input {
float2 uv_MainTex;
float2 uv_BumpMap;
};

void surf(Input IN, inout SurfaceOutput o) {
fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
o.Albedo = tex.rgb * _Color.rgb;
o.Gloss = tex.a;
o.Alpha = tex.a * _Color.a;
o.Specular = _Shininess;
o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_BumpMap));
}
ENDCG
}

FallBack "Transparent/Cutout/VertexLit"
}

Creating x-ray shader in Unity

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/xrayMode" {
Properties{
_Color("_Color", Color) = (0,1,0,1)
_Inside("_Inside", Range(0,1)) = 0
_Rim("_Rim", Range(0,2)) = 1.2
}
SubShader{
Tags{ "Queue" = "Transparent" }
LOD 80

Pass{
Name "Darken"
Cull off
Zwrite off
Blend dstcolor zero

CGPROGRAM

#pragma vertex vert_surf
#pragma fragment frag_surf
#pragma fragmentoption ARB_precision_hint_fastest
//#pragma multi_compile_fwdbase

#include "HLSLSupport.cginc"
#include "UnityCG.cginc"


struct v2f_surf {
half4 pos : SV_POSITION;
fixed4 finalColor : COLOR;
};

uniform half4 _Color;
uniform half _Rim;
uniform half _Inside;

v2f_surf vert_surf(appdata_base v) {
v2f_surf o;

o.pos = UnityObjectToClipPos(v.vertex);
half3 uv = mul((float3x3)UNITY_MATRIX_IT_MV, v.normal);
uv = normalize(uv);
o.finalColor = lerp(half4(1,1,1,1),_Color,saturate(max(1 - pow(uv.z,_Rim),_Inside)));
return o;
}

fixed4 frag_surf(v2f_surf IN) : COLOR{

return IN.finalColor;
}

ENDCG
}

Pass{
Name "Lighten"
Cull off
Zwrite off
Blend oneminusdstcolor one

CGPROGRAM

#pragma vertex vert_surf
#pragma fragment frag_surf
#pragma fragmentoption ARB_precision_hint_fastest
//#pragma multi_compile_fwdbase

#include "HLSLSupport.cginc"
#include "UnityCG.cginc"


struct v2f_surf {
half4 pos : SV_POSITION;
fixed4 finalColor : COLOR;
};

uniform half4 _Color;
uniform half _Rim;
uniform half _Inside;

v2f_surf vert_surf(appdata_base v) {
v2f_surf o;

o.pos = UnityObjectToClipPos(v.vertex);
half3 uv = mul((float3x3)UNITY_MATRIX_IT_MV, v.normal);
uv = normalize(uv);
o.finalColor = lerp(half4(0,0,0,0),_Color,saturate(max(1 - pow(uv.z,_Rim),_Inside)));
return o;
}

fixed4 frag_surf(v2f_surf IN) : COLOR{

return IN.finalColor;
}

ENDCG
}
}

FallBack "Mobile/VertexLit"
}