Wednesday, 15 April 2020

Accessing Camera feed in Unity using C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

public class WebStream : MonoBehaviour
{
    public RawImage rawimage;
    WebCamTexture webCamTexture;

    public Text webCamDisplayText;

    void Start()
    {


        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }
        GoWebCam01();
    }


    //CAMERA 01 SELECT
    public void GoWebCam01()
    {
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }

        webCamTexture = new WebCamTexture(cam_devices[0].name, 480, 640, 30);
        rawimage.texture = webCamTexture;
        if (webCamTexture != null)
        {
            webCamTexture.Play();
            Debug.Log("Web Cam Connected : " + webCamTexture.deviceName + "\n");
        }
        webCamDisplayText.text = "Camera Type: " + cam_devices[0].name.ToString();
    }
    //CAMERA 02 SELECT
    public void GoWebCam02()
    {
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        // for debugging purposes, prints available devices to the console
        for (int i = 0; i < cam_devices.Length; i++)
        {
            print("Webcam available: " + cam_devices[i].name);
        }

        webCamTexture = new WebCamTexture(cam_devices[1].name, 480, 640, 30);
        rawimage.texture = webCamTexture;
        if (webCamTexture != null)
        {
            webCamTexture.Play();
            Debug.Log("Web Cam Connected : " + webCamTexture.deviceName + "\n");
        }
        webCamDisplayText.text = "Camera Type: " + cam_devices[1].name.ToString();
    }
}

Thursday, 14 November 2019

Unity C# Shooting a object along a trajectory

Create a new game object a sphere that will be the object that will be used for shooting, also create an empty game object and name it as a target. Copy the below script and attach it to a new empty game object and attach the sphere and target object in the inspector.


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

public class ShootingBall : MonoBehaviour
{
    public Transform myTarget;
    public GameObject snowballs;
    float shootAngle = 30;
    float angle;
    // Start is called before the first frame update
    public Vector3 BallisticVel(Transform target, float angle)
    {
        Vector3 dir = target.position - transform.position;
        float h = dir.y;  // get height difference
        dir.y = 0;  // retain only the horizontal direction
        float dist = dir.magnitude;  // get horizontal distance
        float a = angle * Mathf.Deg2Rad;  // convert angle to radians
        dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
        dist += h / Mathf.Tan(a);  // correct for small height differences
                                   // calculate the velocity magnitude
        var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
        return vel * dir.normalized;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("b"))
        {  // press b to shoot
            GameObject ball = Instantiate(snowballs, transform.position, Quaternion.identity);
            ball.GetComponent<Rigidbody>().velocity = BallisticVel(myTarget, shootAngle);
            Destroy(ball, 10);
        }
    }
}

Wednesday, 5 June 2019

Learning's: Unity C# Parsing JSON data using SimpleJSON

Learning's: Unity C# Parsing JSON data using SimpleJSON: 1. Download the SimpleJSON .cs from this link and  https://github.com/Bunny83/SimpleJSON and create a folder called "plugin" un...

Unity C# Parsing JSON data using SimpleJSON


1. Download the SimpleJSON .cs from this link and https://github.com/Bunny83/SimpleJSON
and create a folder called "plugin" under unity project assets folder and place the SimpleJSON.cs script inside.

2. Create a new class called as SampleJSONParsing

3. Paste the below code on to the newly created class.

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


public class SampleJSONParsing :MonoBehaviour
{

    string encodedString = "{\"method\": \"retrieve_configuration\",\"params\": {\"configuration\" :\"109873839\"}}";

    void Start()
    {
        JSONNode jsonNode = SimpleJSON.JSON.Parse(encodedString);
        string action = jsonNode["params"][0].Value;
        Debug.Log(action);
    }


}

4. create a new scene attach the script to an empty game object and run the scene.

5. Similarly to parse your data pass it as a string.

Tuesday, 21 May 2019

Unity C# Sorting and Displaying Mesh Renderers in layers

1. Create a new C# script as "SetSortingLayer" and paste the below contents.
2. Attach the script to game objects with Mesh Renderers set the sorting layer. 0 being the lowest of the base layer and the top layer goes 0n increment



using UnityEngine;

 [ExecuteInEditMode]
 public class SetSortingLayer : MonoBehaviour {
     public Renderer MyRenderer;
     public string MySortingLayer;
     public int MySortingOrderInLayer;
   
     // Use this for initialization
     void Start () {
         if (MyRenderer == null) {
             MyRenderer = this.GetComponent<Renderer>();
         }
           

         SetLayer();
     }


     public void SetLayer() {
         if (MyRenderer == null) {
             MyRenderer = this.GetComponent<Renderer>();
         }
           
         MyRenderer.sortingLayerName = MySortingLayer;
         MyRenderer.sortingOrder = MySortingOrderInLayer;
       
         //Debug.Log(MyRenderer.sortingLayerName + " " + MyRenderer.sortingOrder);
     }
 
 }

Monday, 20 May 2019

Unity C# - Hololens Creating an intractable model on Run time

To attach a script to a game object as component during run time, create a new C# script  and paste the below contents.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HoloToolkit.Unity.InputModule.Utilities.Interactions;

public class AttachScript : MonoBehaviour
{
    public GameObject  DmuModel;

    void Start()
    {
         Transform[] allchild = DmuModel.GetComponentsInChildren<Transform>();
           foreach (Transform child in allchild)
             {

              child.gameObject.AddComponent<MeshCollider>();
               child.gameObject.AddComponent<TwoHandManipulatable>();
           }

    }

}

Monday, 13 May 2019

3D Text Mesh Wrapping in Unity using C#

To use the text mesh wrapper snippet create a new 3D Text component in unity and then create a new C# script and name it as "WrapText" and replace the content with the below code snippet.

Then attach the code to the 3D text mesh  and under the 'Text Mesh" field in Wrap text component drag the same 3D text mesh.

Under the Max Line Chars field you can set the length of a particular sentence.

That's  it.

-------CODE SNIPPET-------------------COPY THE BELOW CONTENT-------------------------

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class WrapText : MonoBehaviour
{
    public TextMesh textMesh;

    public int maxLineChars = 35;
    private int lastMaxLineChars = 35;

    string wrappedText = "";
    public bool disableWhilePlaying = true;

    void Awake()
    {
       // bool shouldDisable = disableWhilePlaying  !(Application.isEditor  !Application.isPlaying);
       // this.enabled = !shouldDisable;
    }

    void Update()
    {
        if (textMesh.text != wrappedText || maxLineChars != lastMaxLineChars)
        {
            int charCount = 0;
            wrappedText = "";
            string line = "";

            char[] separators = new char[] { ' ', '\n', '\t' };
            string[] words = textMesh.text.Split(separators);

            for (int i = 0; i < words.Length; i++)
            {
                string word = words[i].Trim();

                if (i == 0)
                {
                    line = word;
                    charCount = word.Length;
                }
                else
                {
                    if ((charCount + (charCount > 0 ? 1 : 0) + word.Length) <= maxLineChars)
                    {
                        if (charCount > 0)
                        {
                            line += ' ';
                            charCount += 1;
                        }

                        line += word;
                        charCount += word.Length;
                    }
                    else
                    {
                        if (wrappedText.Length > 0)
                            wrappedText += '\n';

                        wrappedText += line;

                        line = word;
                        charCount = word.Length;
                    }
                }
            }

            if (charCount > 0)
            {
                if (wrappedText.Length > 0)
                    wrappedText += '\n';

                wrappedText += line;
            }

            textMesh.text = wrappedText;
            lastMaxLineChars = maxLineChars;
        }
    }
}