Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Scene Load Duplicates Main Camera??

Discussion in '2D' started by Lucario, Mar 5, 2016.

  1. Lucario

    Lucario

    Joined:
    Mar 24, 2015
    Posts:
    21
    Hi guys!
    I'm having a bit of an issue with my scene load and reload for my multilevel game. Every time I beat a level in my game and change the scene, a duplicate of my Main camera is made. This messes with all of my screentoworld stuff with my mouseposition and aiming of my player. How can I make sure that a second main camera isn't created when I load a scene?
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,134
    cameras cannot create them themself. Do you use DontDestroyOnLoad ? Or something in new level add new camera.
     
    Last edited: Mar 6, 2016
  3. rslnautic

    rslnautic

    Joined:
    Nov 16, 2015
    Posts:
    5
    Use singleton construction pattern, inside your camera script to have only one instance of your camera.
    It will fix your problem of duplication.
    If you have other duplication problem like player or gamemanager use singleton! :)

    Code (CSharp):
    1. public class Camera2D : MonoBehaviour {
    2.     //Singleton
    3.     private static Camera2D _instance;
    4.     public static Camera2D Instance { get { return _instance; } }
    5.  
    6.     private void Awake()
    7.     {
    8.         //Singleton
    9.         if (_instance != null && _instance != this)
    10.         {
    11.             Destroy(this.gameObject);
    12.         } else {
    13.             _instance = this;
    14.         }
    15.     }
    16. }