In the Asset window, right-click and select Create, followed by C# Script.

Rename the new C# Script "ArduinoCtrl".

Edit the C# Script

Right-click the ArduinoCtrl C# Script and select Open C# Project. This opens the script in Visual Studio so that you can edit the code.

In the Visual Studio window, copy and paste the C# code from below into the ArduinoCtrl file. Then, Save the file.

// SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
//
// SPDX-License-Identifier: MIT

using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using UnityEngine;
using UnityEngine.UI;

public class arduinoCtrl : MonoBehaviour
{
    // replace with your board's COM port
    SerialPort stream = new SerialPort("COM52", 9600);

    public Transform t;

    void Start()
    {
        stream.Open();
    }

    void Update()
    {
        Vector3 lastData = Vector3.zero;

        string UnSplitData = stream.ReadLine();
        print(UnSplitData);
        string[] SplitData = UnSplitData.Split('|');

        float AccX = float.Parse(SplitData[1]);
        float AccY = float.Parse(SplitData[2]);
        float AccZ = float.Parse(SplitData[3]);

        lastData = new Vector3(AccX, AccY, AccZ);

        t.transform.rotation = Quaternion.Slerp(t.transform.rotation, Quaternion.Euler(lastData), Time.deltaTime * 2f);

    }
}

Update the Port Name

Update the SerialPort object with your Arduino board's port name. You can find this information in the Arduino IDE under Tools - Port.

stream = new SerialPort("COM19", 9600);

Update the API Compatibility Level

In the main Unity project window, click on Edit and then Project Settings... Click on Player and scroll down to the Configuration settings under Other Settings. Change the Api Compatibility Level* to .NET Framework. This allows all of the expected Unity Visual Studio libraries to work as expected in the C# script.

Apply the C# Script to the 3D Object

In the Asset window, drag the ArduinoCtrl file to the 3D object in the Hierarchy window. You'll see the ArduinoCtrl script appear in the object's Inspector window.

In the T box, click on and select your 3D object from the list. This applies the script to the object to control its rotational movement.

This guide was first published on Aug 31, 2022. It was last updated on Apr 24, 2024.

This page (Unity C# Script) was last updated on Apr 24, 2024.

Text editor powered by tinymce.