- Home /
Laying prefabs end to end
If one wants to have two prefabs of different types in a line horizontally how would one accomplish this using c#? Currently I am trying to do the following: public void Spawn () {
GameObject g = ((GameObject)Instantiate (hills [Random.Range (0, hills.Length)], new Vector3 (0.0f, transform.position.y, transform.position.z), Quaternion.identity));
g.transform.position = new Vector3 ((subs [subs.Count - 1].transform.position.x + (g.renderer.bounds.size.x) + (subs [subs.Count - 1].renderer.bounds.size.x) / 2), transform.position.y, transform.position.z);
g.transform.parent = this.transform;
subs.Add (g);
}
where hills is an array of prefabs to spawn and subs is an arraylist containing spawned prefabs. However this doesn't work properly as I get spaces between them and I get them overlapping. What is the correct way to do this? This is in unity 2D.
Answer by Narv · Feb 14, 2014 at 06:59 PM
Why not put an empty game object in the hierarchy for the prefabs at the left and right ends (or wherever you want them). Then snap those game objects together? Position of the left game object would be equal to the position of the right game object from the other prefab (or however it is your logic would set them up). Then you could shift the entire hill object to match where the empty game object is.
Just keep in mind you would need to standardized how you do your game objects in that they would need to always be at the absolute edge (or at least, consistent to where they match) and follow a naming scheme so the code could find them and get their transform.
Your answer
Follow this Question
Related Questions
Issue Instantiating prefab in C# 0 Answers
How do I make a clone of a prefab appear on the correct layer? [5.2.2f1] 1 Answer
Instantiate a GameObject from a Prefab without using an original to clone 1 Answer
Setting parent of instantiated object fails (Error: setting parent of prefab is disabled...) 1 Answer
Networkview on prefab consumes bandwidth or safe to use? 0 Answers