Different result in built game and play mode.

  • I create a camera, a rendertexture and a material in my code. I set camera’s target texture to the rendertexture, set material’s main texture to the rendertexture, and attach the material to my cube.
    In play mode, I get the correct result - a cube with the camera view. But in built game, the camera is null, and the cube is in default sprite.
    Enviorment : Universal RP, Cinemachine
    In Awake() method:

          GameObject cameraObject = new GameObject();
          _camera = cameraObject.AddComponent<Camera>();
          _camera.orthographic = true;
          _camera.targetTexture = _renderTexture;
          _cameraBrain = _camera.gameObject.AddComponent<CinemachineBrain>();
          _camera.orthographicSize = _defaultOrthographicSize;
          GameObject vitualCameraObject = new GameObject();
          vitualCameraObject.transform.parent = transform;
          _vitualCamera = vitualCameraObject.AddComponent<CinemachineVirtualCamera>();
          CinemachineConfiner confiner = vitualCameraObject.AddComponent<CinemachineConfiner>();
          confiner.m_BoundingShape2D = transform.Find("Confine Box").GetComponent<PolygonCollider2D>();
          _vitualCamera.AddExtension(confiner);
          _vitualCamera.m_Lens.OrthographicSize = _defaultOrthographicSize;`  
    

Play mode in editor:
[194485-qq截图20220327013624.png|194485]
Built game:
[194486-qq截图20220327013649.png|194486]

  • To debug, I change the UI ammo amount to camera’s name. But in built game, the camera is null, the changing code isn’t be run successful. *
  • I have a Main Camera to render the cubes.*

It’s not better to prepare prefab with all Components and just Instantiate that prefab?

Its a roguelike game, the cubes(rooms) is random.