Search Unity

Bug Player Input Component Loses Camera Reference when Prefab is Instantiated

Discussion in 'Prefabs' started by reddylant, Oct 4, 2022.

  1. reddylant

    reddylant

    Joined:
    Aug 15, 2020
    Posts:
    3
    Unity version 2021.3.2f1

    I'm manually spawning in a player prefab and feeding it info it needs. SpawnPlayer.PNG
    However, when I instantiate the object the Camera section is goes blank despite me assigning it in the prefab.

    PlayerPrefabComponents.PNG
    LostCamera.PNG

    I've even tried manually setting the camera field through script but it gets ignored for some reason. Has anyone else experienced this issue?
     
    Last edited: Oct 4, 2022
  2. Mads-Nyholm

    Mads-Nyholm

    Unity Technologies

    Joined:
    Aug 19, 2013
    Posts:
    219
    In line 21 you are overwriting the
    input.camera
    that was assigned in the Inspector?
     
  3. reddylant

    reddylant

    Joined:
    Aug 15, 2020
    Posts:
    3
    That's my attempt at doing it manually, even without that line the same problem occurs
     
  4. reddylant

    reddylant

    Joined:
    Aug 15, 2020
    Posts:
    3
    I've figured out what is breaking my camera. In the code above I'm using PlayerInput.Instantiate to spawn in the player prefab which causes the camera field to be blank and also breaks the camera component all together making it not display anything. When I switch to the regular Instantiate method it fixes this issue, however I lose the ability to set the players index and splitscreen index which I really need to be able to control. Does anyone know why PlayerInput.Instantiate breaks the camera? Is there another way I can set the player index and splitscreen index? I've tried looking up a solution and haven't found one.
     
  5. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    That is trying to grab a camera from the same GameObject, but the camera is on a child object. So your code is introducing the bug no matter what Instantiate does or does not do.


    I hadn't seen PlayerInput.Instantiate before and uuuuh, it's a bit cursed? It sets a bunch of static properties, instantiates the object, and then resets those properties. Then PlayerInput's OnEnable does, eventually, check if those static properties are set and then it copies those. That's not even in the vicinity of good code practice, in Unity or anywhere else.

    Like... why not at least do a GetComponentInChildren for the values? Why not, uh, have a simple Initialize method that you call after you Object.Instantiate the thing?