I’m making a C# version of Slither.io and I have movement sorted, and I can get the first segment to follow the snakes head fine. But when the second segment of the snake spawns, it too follows the head and not the segment above. All I can think to do is attach a new script to every segment with the above segment as the leader, but I can imagine this will get intensive. Any suggestions?
1 Answer
1Have you follow script store a public int, when you instantiate that prefab body part give it a number so the head is 0, the first body part gets 1 then second gets 2. Also rename the body part when instantiating so the name is either the number itself or something that contains the number (e,.g, BodyPart1).
Now have the script search for the GameObject 1 lower than it’s own number. You might have to do a check in Update to pick up the GameObject if it’s not been found in Awake but just try Awake first.
So
GameObject go = Instantiate (myPrefab, transform.position, Quaternion.identity) as GameObject;
That instantiates your prefab but assigns it a temporary GameObject so you can find components and edit them.
go.GetComponent<MyScript>().MyInt = i;
go.name = "BodyPart" + i.ToString();
This assumes your script is MyScript and it has a public int called MyInt and that i is an int for the current number of the body part.
Then check for what to follow.
private int parentInt;
private string folowName;
private GameObject follow;
void Start(){
parentInt = MyInt - 1;
followName = "BodyPart" + parentInt.ToString();
follow = GameObject.Find(followName);
The Find is wasteful and I’m typing this without testing so there may well be typos but as you increase i each time you call instantiate the body part gets a higher number and also knows to follow the previous GameObject rather than the head.
Well that turned into a wall of text!