- Home /
Separate GameObject name?
I have several GameObjects with the name "Waypoint 1", "Waypoint 2", "Waypoint 3"... "Waypoint 600"...
Now, Is there a way I can code in a way that I can read and write just the number part of the GameObject's name?
For example I want that if my player is at "Waypoint 20" the game adds 10 to the name and as a result an object spawns at "Waypoint 30" or the player is at "Waypoint 40" the object spawns at "Waypoint 50", I mean these are just examples but how can I do something like this?
What I'm reading is the GameObject name (print(hit.collider.name);)
Answer by Xavier78 · May 08, 2018 at 01:58 AM
I would make a waypoint class, and have it get assigned its value manually, and then either have a manager that keeps track of all the way points so you can do something like
offset = 10;
wayPointAhead = WayPointManager.GetWaypoint(WayPointManager.CurrentWayPoint.Number + offset);
wayPointAhead.gameObject;
or have it be a node that has a reference to the next way point, so you can go down ten waypoints.
That way is a lot more efficent then comparing strings, but if you really just want the string do something like.
string name = gameObject.name;
float wayPointNumber;
float.TryParse(name.Replace("Waypoint ", ""), out wayPointNumber);
yes thanks a lot it worked with something like:
int.TryParse(currentWaypoint.Replace("Waypoint ", ""), out wayPointNumber);
wayPointNumber += 15;
string newWaypoint = "Waypoint " + wayPointNumber;
newPoint = GameObject.Find(newWaypoint);
spawnPoint = newPoint.GetComponent<Transform>();
GameObject selectedCar = Object.Instantiate(trafficCars[selection], spawnPoint.position, spawnPoint.rotation);
Problem with this is that I can't modify the Waypoint objects another asset generates them and uses them but I'm managing to squeeze a little extra juice out of them
Answer by JimmyCushnie · May 08, 2018 at 02:00 AM
You can remove stuff from a string using String.Replace. So to get just the number part of the name, you can do hit.collider.name.Replace("Waypoint ", "")
.
However, using strings is a bad way to get numbers. I would instead make a monobehaviour for waypoints with an integer stored in it. Then, to get the waypoint number, you'd do something like hit.collider.GetComponent<Waypoint>().number
.
Your answer
![](https://koobas.hobune.stream/wayback/20220612162225im_/https://answers.unity.com/themes/thub/images/avi.jpg)