Esempio n. 1
0
    public override void OnInspectorGUI()
    {
        if (testSource == null)
        {
            var go = new GameObject("testSource");
            go.hideFlags = HideFlags.HideAndDontSave;
            testSource   = go.AddComponent <AudioSource>();
        }
        var sd = (SoundDef)target;

        // Allow playing audio even when sounddef is readonly
        var oldEnabled = GUI.enabled;

        GUI.enabled = true;
        if (testSource.isPlaying && GUILayout.Button("Stop []"))
        {
            testSource.Stop();
        }
        else if (!testSource.isPlaying && GUILayout.Button("Play >"))
        {
            SoundSystemBase.StartSource(testSource, sd);
        }
        GUI.enabled = oldEnabled;

        DrawPropertiesExcluding(serializedObject, new string[] { "m_Script" });

        serializedObject.ApplyModifiedProperties();
    }
Esempio n. 2
0
    /// <summary>
    /// This initialization method should be called by SoundSystem classes only.
    /// </summary>
    /// <param name="soundSystem">Sound system handling this sound object.</param>
    /// <param name="soundType">Type of sound this object contains.</param>
    /// <param name="startMuted">Whether sound should start muted.</param>
    public bool Initialize(SoundSystemBase soundSystem, SoundInfo.SoundType soundType, bool startMuted)
    {
        if (soundSystem == null)
        {
            return(false);
        }
        m_soundSystem = soundSystem;
        m_soundType   = soundType;

        // Get this object's AudioSource component (either attached to itself or to its children)
        m_audioSource = this.GetComponentInChildren <AudioSource>();
        // One-shot sounds do not loop
        if (m_soundType == SoundInfo.SoundType.ONE_SHOT)
        {
            m_audioSource.loop = false;
        }
        // If initialized by SoundSystem as muted, consider this muted via MuteAll
        if (startMuted)
        {
            Mute(true);
        }

        return(true);
    }
Esempio n. 3
0
 public static void ProvideSoundSystem(SoundSystemBase soundSystem)
 {
     m_soundSystem = soundSystem;
 }
Esempio n. 4
0
    /*
     * THIS CAUSES RANDOM CRASHES
     *
     * private static void PreLoadAnimationNodes()
     * {
     *          // In Editor, convince Burst to JIT compile all Animation UNode types immediately.
     #if UNITY_EDITOR
     *          var start = UnityEngine.Time.realtimeSinceStartup;
     *          var wasSyncCompile = Menu.GetChecked("Jobs/Burst/Synchronous Compilation");
     *          Menu.SetChecked("Jobs/Burst/Synchronous Compilation", true);
     *          try
     *          {
     *              var animAssembly = typeof(Unity.Animation.AnimationGraphSystem).Assembly;
     *              var unodeNonGenericTypes = animAssembly.GetTypes().Where(t =>
     *                  t.IsClass && !t.IsAbstract && !t.IsGenericType &&
     *                  typeof(Unity.DataFlowGraph.INodeFunctionality).IsAssignableFrom(t));
     *              var unodeGenericTypesReferencedInData = animAssembly.GetTypes()
     *                  .Where(t => !t.IsClass && typeof(Unity.DataFlowGraph.INodeData).IsAssignableFrom(t))
     *                  .Select(t => t
     *                      .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
     *                      .Select(fi => fi.FieldType)
     *                      .Where(ft => ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Unity.DataFlowGraph.NodeHandle<>))
     *                      .Select(ft => ft.GetGenericArguments()[0])
     *                      .Where(ft => ft.IsGenericType))
     *                  .SelectMany(t => t)
     *                  .Distinct();
     *
     *              var nodeSet = new Unity.DataFlowGraph.NodeSet();
     *
     *              MethodInfo getFunctionality = nodeSet.GetType().GetMethod("GetFunctionality", new System.Type[0]);
     *              foreach (System.Type t in unodeNonGenericTypes.Concat(unodeGenericTypesReferencedInData))
     *                  getFunctionality.MakeGenericMethod(t).Invoke(nodeSet, null);
     *
     *              nodeSet.Dispose();
     *
     *              Debug.Log($"Compilation of Animation UNode types took {UnityEngine.Time.realtimeSinceStartup - start} seconds");
     *          }
     *          finally
     *          {
     *              Menu.SetChecked("Jobs/Burst/Synchronous Compilation", wasSyncCompile);
     *          }
     #endif
     * }
     */

    public void Awake()
    {
        GameDebug.Assert(game == null);
        DontDestroyOnLoad(gameObject);
        game = this;

        GameApp.IsInitialized = true;

        //PreLoadAnimationNodes();

        m_StopwatchFrequency = System.Diagnostics.Stopwatch.Frequency;
        m_Clock = new System.Diagnostics.Stopwatch();
        m_Clock.Start();

#if UNITY_EDITOR
        _buildUnityVersion = InternalEditorUtility.GetFullUnityVersion();
#endif
        var buildInfo = FindObjectOfType <BuildInfo>();
        if (buildInfo != null)
        {
            _buildId           = buildInfo.buildId;
            _buildUnityVersion = buildInfo.buildUnityVersion;
        }

        var commandLineArgs = new List <string>(System.Environment.GetCommandLineArgs());

        // TODO we should only initialize this if we have a graphics device (i.e. non-headless)
        Overlay.Managed.Initialize();

#if UNITY_STANDALONE_LINUX
        m_isHeadless = true;
#else
        m_isHeadless = commandLineArgs.Contains("-batchmode");
#endif
        var noconsole           = commandLineArgs.Contains("-noconsole");
        var consoleRestoreFocus = commandLineArgs.Contains("-consolerestorefocus");
        if (noconsole)
        {
            UnityEngine.Debug.Log("WARNING: starting without a console");
            var consoleUI = new ConsoleNullUI();
            Console.Init(buildId, buildUnityVersion, consoleUI);
        }
        else if (m_isHeadless)
        {
#if UNITY_EDITOR
            Debug.LogError("ERROR: Headless mode not supported in editor");
#endif

#if UNITY_STANDALONE_WIN
            string consoleTitle;

            var overrideTitle = ArgumentForOption(commandLineArgs, "-title");
            if (overrideTitle != null)
            {
                consoleTitle = overrideTitle;
            }
            else
            {
                consoleTitle = Application.productName + " Console";
            }

            consoleTitle += " [" + System.Diagnostics.Process.GetCurrentProcess().Id + "]";

            var consoleUI = new ConsoleTextWin(consoleTitle, consoleRestoreFocus);
#elif UNITY_STANDALONE_LINUX
            var consoleUI = new ConsoleTextLinux();
#else
            UnityEngine.Debug.Log("WARNING: starting without a console");
            var consoleUI = new ConsoleNullUI();
#endif
            Console.Init(buildId, buildUnityVersion, consoleUI);
        }
        else
        {
            var consoleUI = Instantiate(Resources.Load <ConsoleGUI>("Prefabs/ConsoleGUI"));
            DontDestroyOnLoad(consoleUI);
            Console.Init(buildId, buildUnityVersion, consoleUI);

            m_DebugOverlay = Instantiate(Resources.Load <DebugOverlay>("DebugOverlay"));
            DontDestroyOnLoad(m_DebugOverlay);
            m_DebugOverlay.Init();

            m_GameStatistics = new GameStatistics();
        }

        // If -logfile was passed, we try to put our own logs next to the engine's logfile
        // if -logfile was set to "-" we forward our logs to Debug.Log, so that it ends up on stdout.
        var engineLogFileLocation = ".";
        var logName             = m_isHeadless ? "game_" + DateTime.UtcNow.ToString("yyyyMMdd_HHmmss_fff") : "game";
        var logfileArgIdx       = commandLineArgs.IndexOf("-logfile");
        var forceForwardToDebug = false;
        if (logfileArgIdx >= 0 && commandLineArgs.Count >= logfileArgIdx)
        {
            var logFile = commandLineArgs[logfileArgIdx + 1];
            if (logFile == "-")
            {
                forceForwardToDebug = true;
            }
            else
            {
                engineLogFileLocation = System.IO.Path.GetDirectoryName(logFile);
            }
        }
        GameDebug.Init(engineLogFileLocation, logName, forceForwardToDebug);

        ConfigVar.Init();

        // Support -port and -query_port as per Multiplay standard
        var serverPort = ArgumentForOption(commandLineArgs, "-port");
        if (serverPort != null)
        {
            Console.EnqueueCommandNoHistory("server.port " + serverPort);
        }

        var sqpPort = ArgumentForOption(commandLineArgs, "-query_port");
        if (sqpPort != null)
        {
            Console.EnqueueCommandNoHistory("server.sqp_port " + sqpPort);
        }

        Console.EnqueueCommandNoHistory("exec -s " + k_UserConfigFilename);

        // Default is to allow no frame cap, i.e. as fast as possible if vsync is disabled
        Application.targetFrameRate = -1;

        if (m_isHeadless)
        {
            Application.targetFrameRate = serverTickRate.IntValue;
            QualitySettings.vSyncCount  = 0; // Needed to make targetFramerate work; even in headless mode

#if !UNITY_STANDALONE_LINUX
            if (!commandLineArgs.Contains("-nographics"))
            {
                GameDebug.Log("WARNING: running -batchmod without -nographics");
            }
#endif
        }
        else
        {
            RenderSettings.Init();
        }

        // Out of the box game behaviour is driven by boot.cfg unless you ask it not to
        if (!commandLineArgs.Contains("-noboot"))
        {
            Console.EnqueueCommandNoHistory("exec -s " + k_BootConfigFilename);
        }

        if (m_isHeadless)
        {
            SoundSystem.Initialize(new SoundSystemNull());
        }
        else
        {
            var soundSystem = new SoundSystemBase();
            soundSystem.Init(audioMixer);
            SoundSystem.Initialize(soundSystem);

            GameObject go = (GameObject)GameObject.Instantiate(Resources.Load("Prefabs/ClientFrontend", typeof(GameObject)));
            UnityEngine.Object.DontDestroyOnLoad(go);
            clientFrontend = go.GetComponentInChildren <ClientFrontend>();
        }

        sqpClient = new SQP.SQPClient();

        GameDebug.Log("A2 initialized");
#if UNITY_EDITOR
        GameDebug.Log("Build type: editor");
#elif DEVELOPMENT_BUILD
        GameDebug.Log("Build type: development");
#else
        GameDebug.Log("Build type: release");
#endif
        GameDebug.Log("BuildID: " + buildId);
        GameDebug.Log("Unity: " + buildUnityVersion);
        GameDebug.Log("Cwd: " + System.IO.Directory.GetCurrentDirectory());

        levelManager = new LevelManager();
        levelManager.Init();
        GameDebug.Log("LevelManager initialized");

        GameDebug.Log("InputSystem initialized");

        // Game loops
        Console.AddCommand("serve", CmdServe, "Start server listening");
        Console.AddCommand("client", CmdClient, "client: Enter client mode.");
        Console.AddCommand("thinclient", CmdThinClient, "client: Enter thin client mode.");
        Console.AddCommand("boot", CmdBoot, "Go back to boot loop");
        Console.AddCommand("connect", CmdConnect, "connect <ip>: Connect to server on ip (default: localhost)");

        Console.AddCommand("menu", CmdMenu, "show the main menu");
        Console.AddCommand("load", CmdLoad, "Load level");
        Console.AddCommand("quit", CmdQuit, "Quits");
        Console.AddCommand("screenshot", CmdScreenshot, "Capture screenshot. Optional argument is destination folder or filename.");
        Console.AddCommand("crashme", (string[] args) => { GameDebug.Assert(false); }, "Crashes the game next frame ");
        Console.AddCommand("saveconfig", CmdSaveConfig, "Save the user config variables");
        Console.AddCommand("loadconfig", CmdLoadConfig, "Load the user config variables");

        Console.AddCommand("profile", CmdProfile, "Run the profiling for a level");

#if UNITY_STANDALONE_WIN
        Console.AddCommand("windowpos", CmdWindowPosition, "Position of window. e.g. windowpos 100,100");
#endif

        Console.SetOpen(true);
        Console.ProcessCommandLineArguments(commandLineArgs.ToArray());
#if UNITY_IOS
        // (marton) This is a hack to work around command line arguments not working on iOS
        if (!Application.isEditor)
        {
            Console.EnqueueCommandNoHistory("preview Level_00");
        }
#endif



        GameApp.CameraStack.OnCameraEnabledChanged += OnCameraEnabledChanged;
        GameApp.CameraStack.PushCamera(bootCamera);
    }
Esempio n. 5
0
    /// <summary>
    /// Updates the initialization process.
    /// </summary>
    private void UpdateInitState()
    {
        switch (m_initState)
        {
        case InitState.NONE:
            AdvanceInitState();
            break;

        case InitState.INIT_SHARED_SYSTEMS:
            // Get references to the shared systems
            m_uiSystem    = this.gameObject.AddDerivedIfNoBase <UISystemBase, UISystem>();
            m_soundSystem = this.gameObject.AddDerivedIfNoBase <SoundSystemBase, SoundSystem>();
            m_dataSystem  = new DataSystem();

            // Initialize shared systems
            m_uiSystem.Initialize();
            m_soundSystem.Initialize();
            m_dataSystem.Initialize();

#if SHOW_STATE_LOGS
            Debug.Log("Initializing shared systems...");
#endif

            AdvanceInitState();
            break;

        case InitState.WAIT_INIT_SHARED_SYSTEMS:
            // Wait for shared systems to finish initialization
#if SHOW_STATE_LOGS
            Debug.Log("Waiting for shared system initialization to finish...");
#endif

            if (m_uiSystem.IsInitialized &&
                m_soundSystem.IsInitialized &&
                m_dataSystem.IsInitialized)
            {
                AdvanceInitState();
            }
            break;

        // TODO: Temporary state - should be moved to different classes
        case InitState.CREATE_SHARED_OBJECTS:
#if SHOW_STATE_LOGS
            Debug.Log("Creating shared objects...");
#endif
            CreateSharedObjects();

            AdvanceInitState();
            break;

        case InitState.INIT_LOCATOR:
#if SHOW_STATE_LOGS
            Debug.Log("Initializing Service Locator...");
#endif
            Locator.ProvideUISystem(m_uiSystem);
            Locator.ProvideSoundSystem(m_soundSystem);
            Locator.ProvideDataSystem(m_dataSystem);

            // If game is loaded from the Main scene (index 0)
            if (Application.loadedLevel == 0)
            {
                AdvanceInitState();
            }
            // If game is loaded from a different scene
            else
            {
                // No need to load a different scene
                // Just load the SceneMaster
                m_initState = InitState.LOAD_SCENE_MASTER;
            }
            break;

        // The following states are cycled through whenever scenes are switched
        case InitState.LOAD_SCENE:
#if SHOW_STATE_LOGS
            Debug.Log("Loading scene...");
#endif
            // Block input while next scene is loading
            m_faderUI.SetBlockInput();

            StartLoading(m_sceneInfo.GetSceneNameOf(m_nextScene));

            AdvanceInitState();
            break;

        case InitState.WAIT_LOAD_SCENE:
            // Wait for scene to finish loading in the background
#if SHOW_STATE_LOGS
            Debug.Log("Waiting for scene to load in the background...");
#endif
            if (m_async != null && m_async.progress >= READY_TO_LOAD_PROGRESS)
            {
                // Start fade out
                if (m_enableFadeAnim)
                {
                    m_faderUI.FadeOut(true);
                }

                AdvanceInitState();
            }
            break;

        case InitState.UNLOAD_CUR_SCENE:
            // If starting from Main scene, there will be nothing to unload
#if SHOW_STATE_LOGS
            Debug.Log("Unloading current scene...");
#endif

            if (Application.loadedLevel == 0 || m_sceneMaster.Unload())
            {
                AdvanceInitState();
            }
            break;

        case InitState.WAIT_UNLOAD_CUR_SCENE:
            // If starting from Main scene, there will be nothing to unload
#if SHOW_STATE_LOGS
            Debug.Log("Waiting for current scene to finish unloading...");
#endif
            if (Application.loadedLevel == 0 || !m_sceneMaster.IsInitialized)
            {
                // If scene fading is enabled, wait for scene to fade out first
                if (!m_enableFadeAnim ||
                    (m_enableFadeAnim && m_faderUI.FaderState == FaderUI.FadeAnimationState.FADED_OUT))
                {
                    // Clean up non-persistent sounds
                    m_soundSystem.DeleteAllSoundObjects(false);

                    AdvanceInitState();
                }
            }
            break;

        case InitState.SWITCH_SCENE:
            // Load the next scene
#if SHOW_STATE_LOGS
            Debug.Log("Switching scene...");
#endif
            ActivateScene();
            // Initialization will continue in OnLevelWasLoaded
            break;

        case InitState.LOAD_SCENE_MASTER:
#if SHOW_STATE_LOGS
            Debug.Log("Loading scene master in scene " + Application.loadedLevelName);
#endif
            if (m_sceneMaster.Load())
            {
                // Provide SceneMaster to the service locator
                Locator.ProvideSceneMaster(m_sceneMaster);

                AdvanceInitState();
            }
            break;

        case InitState.WAIT_LOAD_SCENE_MASTER:
#if SHOW_STATE_LOGS
            Debug.Log("Waiting for scene master to load...");
#endif
            if (m_sceneMaster.IsInitialized)
            {
                // Start fade in
                if (m_enableFadeAnim)
                {
                    m_faderUI.FadeIn();
                }

                AdvanceInitState();
            }
            break;

        case InitState.DONE:
#if SHOW_STATE_LOGS
            if (BuildInfo.IsDebugMode)
            {
                Debug.Log("Main initialization complete");
            }
#endif
            // Switch to IDLE state
            // If the SceneMaster switches the scene, this state change will be overridden
            AdvanceInitState();

            // Update scene enum for the current scene
            m_curScene = m_nextScene;
            // Start the scene - pass control over to the active scene master
            m_sceneMaster.StartScene();
            break;

        case InitState.IDLE:
            break;
        }
    }