File size: 2,092 Bytes
d353048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using UnityEngine;

namespace Unity.MLAgents
{
    /// <summary>
    /// Factory class for an ICommunicator instance. This is used to the <see cref="Academy"/> at startup.
    /// By default, on desktop platforms, an ICommunicator will be created and attempt to connect
    /// to a trainer. This behavior can be prevented by setting <see cref="CommunicatorFactory.Enabled"/> to false
    /// *before* the <see cref="Academy"/> is initialized.
    /// </summary>
    public static class CommunicatorFactory
    {
        static Func<ICommunicator> s_Creator;
        static bool s_Enabled = true;

        /// <summary>
        /// Whether or not an ICommunicator instance will be created when the <see cref="Academy"/> is initialized.
        /// Changing this has no effect after the <see cref="Academy"/> has already been initialized.
        /// </summary>
        public static bool Enabled
        {
            get => s_Enabled;
            set => s_Enabled = value;
        }

#if UNITY_EDITOR
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
        static void ResetStaticsOnLoad()
        {
            s_Creator = null;
            s_Enabled = true;
        }
#endif
        /// <summary>
        /// Check if a communicator has been registered.
        /// </summary>
        public static bool CommunicatorRegistered => s_Creator != null;

        internal static ICommunicator Create()
        {
            return s_Enabled ? s_Creator() : null;
        }

        /// <summary>
        /// Register a function that will create an ICommunicator instance.
        /// </summary>
        /// <param name="creator">Creator</param>
        /// <typeparam name="T">Type of communicator</typeparam>
        public static void Register<T>(Func<T> creator) where T : ICommunicator
        {
            s_Creator = () => creator();
        }

        /// <summary>
        /// Clear the registered creator.
        /// </summary>
        public static void ClearCreator()
        {
            s_Creator = null;
        }
    }
}