Hi,
I’m slightly confused about how to go about extracting some numbers from a string, I’m not sure if even starting the right way.
I’ve got a grid of cubes that i was trying to get their index x,y co-ords, not position, just their relative x, y index ie 0,0, 8,4 etc.
The way I’ve tried to solve it is by giving them a name using point.name = x + “,” + y; and then try and parse it to get them back to ints, but the examples I’ve seen for parsing don’t use multiple variables, so I’m a bit confused as to whether it’s possible.
Is there a way to remove the comma using parsing and split the x and y into two separate ints?
Is this the best way to go about this? Is there another way of getting the index from a transform array?
using UnityEngine;
using System.Collections;
public class TransformGrid : MonoBehaviour {
public Transform prefab;
public int gridResoX = 10;
public int gridResoY = 10;
public int gridResoZ = 10;
private int row;
private int column;
private Vector3 lastPosition;
Transform[] grid;
void Awake ()
{
grid = new Transform[gridResoX * gridResoY];
for (int i = 0, y = 0; y < gridResoY; y++) {
for (int x = 0; x < gridResoX; x++) {
grid[i] = CreatePoints (x, y);
}
}
}
void UpdateMouse()
{
lastPosition = Input.mousePosition;
}
void Update()
{
if (Input.mousePosition != lastPosition) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
if (Input.GetMouseButtonDown (0))
{
UpdateMouse();
DeletePoints (hit.collider.name);
//Debug.Log (hit.collider.name);
}
}
}
}
void DeletePoints(string name)
{
int num = int.Parse(name);
Debug.Log (num);
}
Transform CreatePoints(int x, int y)
{
Transform point = Instantiate<Transform>(prefab);
point.name = x + "," + y;
point.parent = transform;
point.localPosition = GetCoordinates (x, y);
point.GetComponent<MeshRenderer> ().material.color = new Color
(
(float)x / gridResoX,
(float)y / gridResoY,
(float)y / gridResoZ
);
return point;
}
Vector2 GetCoordinates(int x, int y) {
return new Vector2
(
x - (gridResoX - 1) * 0.5f,
y - (gridResoY - 1) * 0.5f
);
}
}