Home > Software engineering >  How do you attach a camera to a spawned player in unity 2d?
How do you attach a camera to a spawned player in unity 2d?

Time:11-23

So I'm working on a simple platformer in unity 2d. I created a level generator that generates random terrain, enemies, and player character right at the start of the level. I want to have the camera follow the player character. I tried using the SetParent() method to set the player character as a child of the Main Camera. I got this error message: "Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption." Is there a way to get around this? Or is there another way I could get my main camera to follow a spawned player character?

Here's the player character spawn potion of my level generator:

                if (x == 1)
                    {
                        Instantiate(player, new Vector3Int(x, y   2, 0), Quaternion.identity);
                        player.transform.SetParent(MainCamera);
                    }

Any assistance would be most appreciated. Thanks!!

CodePudding user response:

Prefabs have no parent, which is why you are getting that problem.

Modifying player is modifying a prefab. However, you mean to modify the instance made from that prefab. You need to get the result of Instantiate and modify that.

You probably also want to save it for reference later, so adding a field for that is appropriate.

Altogether:

private GameObject playerInstance; 

// ...  

playerInstance = Instantiate(player, new Vector3Int(x, y   2, 0), Quaternion.identity); 
playerInstance.transform.SetParent(MainCamera.transform);

Or, if you'd like to make the camera a child of your player so that it follows the player automatically. If doing this, you probably also want to set the worldPositionStays parameter of SetParent to be false, so that the camera keeps its local position when the parent is set.

private GameObject playerInstance; 

// ...  

playerInstance = Instantiate(player, new Vector3Int(x, y   2, 0), Quaternion.identity); 
mainCamera.transform.SetParent(playerInstance.transform, false);

CodePudding user response:

Try directly assigning the parent as an instance of your prefab, then zero'ing the Camera's local transform:

GameObject myPlayer = Instantiate(player, new Vector3Int(x, y   2, 0), Quaternion.identity); //GameObject can be whatever object type player is
myPlayer.transform.parent = MainCamera.transform;
MainCamera.transform.localPosition = Vector3.zero;
  • Related