- Home /
Position of cameras children objects messed up after the game start.
Hi! I am creating my first 2d game in unity and I have created a project with a camera and StatickBackground child object that supposed to move with camera. The camera is then following a player game object. At the beginning of the game, static background is only 1 star and others will be cloned in code after the game starts.
public class CreateStaticBg : MonoBehaviour
{
public UnityEngine.GameObject stars;
public static readonly Random rand = new Random(1234);
void Start()
{
for (int i = rand.Next(500) + 10; i >= 0; i--)
Instantiate(stars, new Vector3(rand.Next(-8000, 8000), rand.Next(-5000, 5000), transform.position.z), Quaternion.identity, transform);
}
}
And camera follow code that is attached to MainCamera object:
public class CameraFollow : GameObject
{
public Transform trans;
void Update()
{
transform.position = new Vector3(trans.position.x, trans.position.y, -20);
}
}
As you can see everything is aligned perfectly since the game is in editor mode and is not playing.
https://answers.unity.com/storage/temp/170233-in-editor.png
However, when I start the game, static background suddenly moves to the x 0 of the world and not stays on the parent ones.
https://answers.unity.com/storage/temp/170234-after-play.png
I have a theory that this is somehow caused by star generation however stars are generated in both left and right from point 0 of StaticBackground. I also tried to set the position of static background back to 0 but this also did not help. The only thing that help was to manually grab the static background in scene view and put it where it supposed to be... In this case its X will end on ~ -6000 which only gives to my theory that static background somehow detaches itself from the camera parent move to [0, 0] of the world and come back to camera.
Any ideas about why is this happening and how to fix it?
Please help.
Your answer
Follow this Question
Related Questions
Parenting an object changes its transform. 0 Answers
Prevent Grabbed Object from Clipping 1 Answer
parent child object 1 Answer
Need help updating camera position to go above the player 2 Answers