C# (Unity)
How to use NEP in Unity?
Version
Link
Nep master port
Installation:
Sample code for sending and reading cube 3D position
using UnityEngine;
using Nep;
using NepGeometryMsgs;
using Newtonsoft.Json;
public class move : MonoBehaviour
{
private NepPublisher pub;
private NepNode node;
private Transform cubeTransform;
private NepVector3 vector;
NepVector3 result;
/// <summary>
/// Represents the message structure for publishing the cube position.
/// </summary>
private class Msg
{
public double message { get; set; }
}
private NepCallback nepCallback;
/// <summary>
/// Callback method to handle incoming messages.
/// </summary>
/// <param name="message">The received message.</param>
private void PrintDataCallback(string message)
{
// Log the X, Y, and Z components of the NepVector3 object
result = JsonConvert.DeserializeObject<NepVector3>(message);
Debug.Log("X:" + result.x.ToString() +
", Y:" + result.y.ToString() + ", Z:" + result.z.ToString());
}
// Start is called before the first frame update
void Start()
{
cubeTransform = GetComponent<Transform>();
node = new NepNode("basic_pub_cs");
vector = new NepVector3();
result = new NepVector3();
// Define the NepCallback/Subscriber for receiving messages
nepCallback = node.NewCallback("test", PrintDataCallback);
nepCallback.Start();
// Define the Publisher for sending messages
pub = node.NewPub("test", "json");
}
// Update is called once per frame
void Update()
{
// Get the position of the cube
Vector3 cubePosition = cubeTransform.position;
// Fill message to send
vector.x = cubePosition.x;
vector.y = cubePosition.y;
vector.z = cubePosition.z;
// Send the message
pub.Publish(vector);
// Update the NepCallback to process received messages
nepCallback.UpdateMessage();
}
private void OnDestroy()
{
// Dispose the Publisher and close the Node
pub.Dispose();
node.Close();
// Stop the NepCallback
nepCallback.Stop();
}
}Solving issues with Newtonsoft.Json
Last updated