i am writing a gcode reader in unity using c# script i have the following code but it does not work i dont know where is the problem and also i dont know where should i attach my script to
code :
using UnityEngine;
using System.Collections;
public class CNCController : MonoBehaviour
{
public GameObject linearAxisX; // The GameObject representing the X-axis
public GameObject linearAxisY; // The GameObject representing the Y-axis
public GameObject linearAxisZ; // The GameObject representing the Z-axis
public float feedRate = 1.0f; // Speed at which the axes move
private string[] gCodeLines; // Array to hold each line of the GCode
private int currentLineIndex; // Index to keep track of the current line being processed
private bool isMoving; // Flag to check if the axes are currently moving
void Start()
{
currentLineIndex = 0;
// Define the GCode commands directly here (Example GCode commands)
string gCodeCommands = @"
G0 X50 Y30 Z10
G1 X100 Y70 Z40
G1 X150 Y100 Z60
";
// Split the input text by new lines to get individual GCode commands
gCodeLines = gCodeCommands.Split('\n');
}
void Update()
{
if (!isMoving)
{
StartCoroutine(ExecuteGCode());
}
}
private IEnumerator ExecuteGCode()
{
isMoving = true;
while (currentLineIndex < gCodeLines.Length)
{
string line = gCodeLines[currentLineIndex];
ProcessGCodeLine(line);
currentLineIndex++;
yield return new WaitForSeconds(1.0f / feedRate);
}
isMoving = false;
}
private void ProcessGCodeLine(string line)
{
// Assuming G0 and G1 commands are in the form "Gx X[value]" where x can be 0, 1, or 2 for X, Y, or Z-axis respectively.
if (line.StartsWith("G0") || line.StartsWith("G1"))
{
string[] tokens = line.Split(' ');
foreach (string token in tokens)
{
if (token.StartsWith("X"))
{
// Extract the value after 'X' and convert it to a float
float targetPositionX = float.Parse(token.Substring(1));
// Move the X-axis to the target position
linearAxisX.transform.position = new Vector3(targetPositionX, linearAxisX.transform.position.y, linearAxisX.transform.position.z);
}
else if (token.StartsWith("Y"))
{
// Extract the value after 'Y' and convert it to a float
float targetPositionY = float.Parse(token.Substring(1));
// Move the Y-axis to the target position
linearAxisY.transform.position = new Vector3(linearAxisY.transform.position.x, targetPositionY, linearAxisY.transform.position.z);
}
else if (token.StartsWith("Z"))
{
// Extract the value after 'Z' and convert it to a float
float targetPositionZ = float.Parse(token.Substring(1));
// Move the Z-axis to the target position
linearAxisZ.transform.position = new Vector3(linearAxisZ.transform.position.x, linearAxisZ.transform.position.y, targetPositionZ);
}
}
}
}
}
