UnityEngine.GameObject.AddComponent()

Here are the examples of the csharp api UnityEngine.GameObject.AddComponent() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

638 Examples 7

19 Source : connectLine.cs
with MIT License
from alchemz

void Start()
    {

        LineRenderer lineRenderer = gameObject.AddComponent<LineRenderer>();
       // lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
        lineRenderer.widthMultiplier = 0.2f;
        lineRenderer.numPositions = lengthOfLineRenderer;

        // A simple 2 color gradient with a fixed alpha of 1.0f.
        float alpha = 1.0f;
        Gradient gradient = new Gradient();
        gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
            );
        lineRenderer.colorGradient = gradient;
    }

19 Source : DifficultySelectionViewController.cs
with MIT License
from andruzzzhka

[UIAction("#post-parse")]
        public void SetupViewController()
        {
            playButtonGlow = playButton.GetComponent<Glowable>();

            levelDetailsRect.gameObject.AddComponent<Mask>();

            Image maskImage = levelDetailsRect.gameObject.AddComponent<Image>();

            maskImage.material = Sprites.NoGlowMat;
            maskImage.sprite = Resources.FindObjectsOfTypeAll<Sprite>().First(x => x.name == "RoundRectPanel");
            maskImage.type = Image.Type.Sliced;
            maskImage.color = new Color(0f, 0f, 0f, 0.25f);

            levelCoverImage.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);

            progressBarBG.color = new Color(1f, 1f, 1f, 0.2f);
            progressBarTop.color = new Color(1f, 1f, 1f, 1f);

            charactertisticControlBlocker.color = new Color(1f, 1f, 1f, 0f);
            difficultyControlBlocker.color = new Color(1f, 1f, 1f, 0f);

            cancellationToken = new CancellationTokenSource();

            _defaultArtworkTexture = Resources.FindObjectsOfTypeAll<Texture2D>().First(x => x.name == "DefaultSongArtwork");

            _playerDataModel = Resources.FindObjectsOfTypeAll<PlayerDataModel>().First();
        }

19 Source : MultiplayerResultsViewController.cs
with MIT License
from andruzzzhka

[UIAction("#post-parse")]
        public void SetupViewController()
        {
            levelDetailsRect.gameObject.AddComponent<Mask>();

            Image maskImage = levelDetailsRect.gameObject.AddComponent<Image>();

            maskImage.material = Sprites.NoGlowMat;
            maskImage.sprite = Resources.FindObjectsOfTypeAll<Sprite>().First(x => x.name == "RoundRectPanel");
            maskImage.type = Image.Type.Sliced;
            maskImage.color = new Color(0f, 0f, 0f, 0.25f);

            levelCoverImage.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);

            _beatmapLevelsModel = Resources.FindObjectsOfTypeAll<BeatmapLevelsModel>().First();

            _defaultArtworkTexture = Resources.FindObjectsOfTypeAll<Texture2D>().First(x => x.name == "DefaultSongArtwork");

            leaderboardTableView.GetComponent<TableView>().RemoveReusableCells("Cell");

            if (selectedLevel != null)
                SetContent(selectedLevel);
        }

19 Source : PlayingNowViewController.cs
with MIT License
from andruzzzhka

[UIAction("#post-parse")]
        public void SetupViewController()
        {
            playNowButtonGlow = playNowButton.GetComponent<Glowable>();

            levelDetailsRect.gameObject.AddComponent<Mask>();

            Image maskImage = levelDetailsRect.gameObject.AddComponent<Image>();

            maskImage.material = Sprites.NoGlowMat;
            maskImage.sprite = Resources.FindObjectsOfTypeAll<Sprite>().First(x => x.name == "RoundRectPanel");
            maskImage.type = Image.Type.Sliced;
            maskImage.color = new Color(0f, 0f, 0f, 0.25f);

            levelCoverImage.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);

            progressBarBG.color = new Color(1f, 1f, 1f, 0.2f);
            progressBarTop.color = new Color(1f, 1f, 1f, 1f);

            //_beatmapLevelsModel = Resources.FindObjectsOfTypeAll<BeatmapLevelsModel>().First();

            _defaultArtworkTexture = Resources.FindObjectsOfTypeAll<Texture2D>().First(x => x.name == "DefaultSongArtwork");

            _playerDataModel = Resources.FindObjectsOfTypeAll<PlayerDataModel>().First();

            leaderboardTableView.GetComponent<TableView>().RemoveReusableCells("Cell");

            if (selectedLevel != null)
                SetSong(selectedLevel, selectedBeatmapCharacteristic, selectedDifficulty);
        }

19 Source : UIHelper.cs
with GNU Lesser General Public License v3.0
from angturil

public static HoverHint AddHintText(RectTransform parent, string text)
        {
            var hoverHint = parent.gameObject.AddComponent<HoverHint>();
            hoverHint.text = text;
            var hoverHintController = Resources.FindObjectsOfTypeAll<HoverHintController>().First();
            hoverHint.SetField("_hoverHintController", hoverHintController);
            return hoverHint;
        }

19 Source : TMP_Dropdown.cs
with MIT License
from ashishgopalhattimare

private void SetupTemplate()
        {
            validTemplate = false;

            if (!m_Template)
            {
                Debug.LogError("The dropdown template is not replacedigned. The template needs to be replacedigned and must have a child GameObject with a Toggle component serving as the item.", this);
                return;
            }

            GameObject templateGo = m_Template.gameObject;
            templateGo.SetActive(true);
            Toggle itemToggle = m_Template.GetComponentInChildren<Toggle>();

            validTemplate = true;
            if (!itemToggle || itemToggle.transform == template)
            {
                validTemplate = false;
                Debug.LogError("The dropdown template is not valid. The template must have a child GameObject with a Toggle component serving as the item.", template);
            }
            else if (!(itemToggle.transform.parent is RectTransform))
            {
                validTemplate = false;
                Debug.LogError("The dropdown template is not valid. The child GameObject with a Toggle component (the item) must have a RectTransform on its parent.", template);
            }
            else if (itemText != null && !itemText.transform.IsChildOf(itemToggle.transform))
            {
                validTemplate = false;
                Debug.LogError("The dropdown template is not valid. The Item Text must be on the item GameObject or children of it.", template);
            }
            else if (itemImage != null && !itemImage.transform.IsChildOf(itemToggle.transform))
            {
                validTemplate = false;
                Debug.LogError("The dropdown template is not valid. The Item Image must be on the item GameObject or children of it.", template);
            }

            if (!validTemplate)
            {
                templateGo.SetActive(false);
                return;
            }

            DropdownItem item = itemToggle.gameObject.AddComponent<DropdownItem>();
            item.text = m_ItemText;
            item.image = m_ItemImage;
            item.toggle = itemToggle;
            item.rectTransform = (RectTransform)itemToggle.transform;

            Canvas popupCanvas = GetOrAddComponent<Canvas>(templateGo);
            popupCanvas.overrideSorting = true;
            popupCanvas.sortingOrder = 30000;

            GetOrAddComponent<GraphicRaycaster>(templateGo);
            GetOrAddComponent<CanvasGroup>(templateGo);
            templateGo.SetActive(false);

            validTemplate = true;
        }

19 Source : TMPro_CreateObjectMenu.cs
with MIT License
from ashishgopalhattimare

[MenuItem("GameObject/UI/TextMeshPro - Text", false, 2001)]
        static void CreateTextMeshProGuiObjectPerform(MenuCommand command)
        {

            // Check if there is a Canvas in the scene
            Canvas canvas = Object.FindObjectOfType<Canvas>();
            if (canvas == null)
            {
                // Create new Canvas since none exists in the scene.
                GameObject canvasObject = new GameObject("Canvas");
                canvas = canvasObject.AddComponent<Canvas>();
                canvas.renderMode = RenderMode.ScreenSpaceOverlay;

                // Add a Graphic Raycaster Component as well
                canvas.gameObject.AddComponent<GraphicRaycaster>();

                Undo.RegisterCreatedObjectUndo(canvasObject, "Create " + canvasObject.name);
            }


            // Create the TextMeshProUGUI Object
            GameObject go = new GameObject("TextMeshPro Text");
            RectTransform goRectTransform = go.AddComponent<RectTransform>();

            Undo.RegisterCreatedObjectUndo((Object)go, "Create " + go.name);

            // Check if object is being create with left or right click
            GameObject contextObject = command.context as GameObject;
            if (contextObject == null)
            {
                //goRectTransform.sizeDelta = new Vector2(200f, 50f);
                GameObjectUtility.SetParentAndAlign(go, canvas.gameObject);

                TextMeshProUGUI textMeshPro = go.AddComponent<TextMeshProUGUI>();
                textMeshPro.text = "New Text";
                textMeshPro.alignment = TextAlignmentOptions.TopLeft;
            }
            else
            {
                if (contextObject.GetComponent<Button>() != null)
                {
                    goRectTransform.sizeDelta = Vector2.zero;
                    goRectTransform.anchorMin = Vector2.zero;
                    goRectTransform.anchorMax = Vector2.one;

                    GameObjectUtility.SetParentAndAlign(go, contextObject);

                    TextMeshProUGUI textMeshPro = go.AddComponent<TextMeshProUGUI>();
                    textMeshPro.text = "Button";
                    textMeshPro.fontSize = 24;
                    textMeshPro.alignment = TextAlignmentOptions.Center;
                }
                else
                {
                    //goRectTransform.sizeDelta = new Vector2(200f, 50f);

                    GameObjectUtility.SetParentAndAlign(go, contextObject);

                    TextMeshProUGUI textMeshPro = go.AddComponent<TextMeshProUGUI>();
                    textMeshPro.text = "New Text";
                    textMeshPro.alignment = TextAlignmentOptions.TopLeft;
                }
            }

         
            // Check if an event system already exists in the scene
            if (!Object.FindObjectOfType<EventSystem>())
            {
                GameObject eventObject = new GameObject("EventSystem", typeof(EventSystem));
                eventObject.AddComponent<StandaloneInputModule>();
                Undo.RegisterCreatedObjectUndo(eventObject, "Create " + eventObject.name);
            }

            Selection.activeGameObject = go;
        }

19 Source : TextContainer.cs
with MIT License
from ashishgopalhattimare

protected override void OnRectTransformDimensionsChange()
        {
            // Required to add a RectTransform to objects created in previous releases.
            if (this.rectTransform == null) m_rectTransform = gameObject.AddComponent<RectTransform>();

            if (m_rectTransform.sizeDelta != k_defaultSize)
                this.size = m_rectTransform.sizeDelta;

            pivot = m_rectTransform.pivot;

            m_hasChanged = true;
            OnContainerChanged();
        }

19 Source : ItemAntiClip.cs
with GNU General Public License v3.0
from Athlon007

void Start()
        {
            BoxCollider trigger = gameObject.AddComponent<BoxCollider>();
            trigger.isTrigger = true;
            trigger.size = new Vector3(5.35f, 5f, 5f);
        }

19 Source : CashRegisterBehaviour.cs
with GNU General Public License v3.0
from Athlon007

IEnumerator PackagesCoroutine()
        {
            yield return new WaitForSeconds(2);
            var packages = GameObject.FindGameObjectsWithTag("ITEM").Where(g => g.name == "amis-auto ky package(xxxxx)" && g.activeSelf).ToArray();
            MSCLoader.ModConsole.Log(packages.Length);
            for (int i = 0; i < packages.Length; ++i)
            {
                packages[i].AddComponent<ItemBehaviour>();
                packages[i].GetPlayMakerFSM("Use").GetState("State 1").AddAction(new CustomPackageHandler(packages[i]));
            }
        }

19 Source : CashRegisterBehaviour.cs
with GNU General Public License v3.0
from Athlon007

public override void OnEnter()
        {
            for (int j = 0; j < items.Length; ++j)
            {
                items[j].gameObject.SetActive(true);
                items[j].gameObject.AddComponent<ItemBehaviour>();
                items[j].gameObject.SetActive(false);
            }
            Finish();
        }

19 Source : ShopModItemSpawnCheck.cs
with GNU General Public License v3.0
from Athlon007

void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.name.ContainsAny(items) && other.gameObject.GetComponent<ItemBehaviour>() == null)
            {
                other.gameObject.AddComponent<ItemBehaviour>();
                GameObject gm = other.gameObject;

                // If the object is cd case, find cd inside of it and attach ItemHook to it.
                if (gm.name == "cd case(itemy)")
                    foreach (var t in gm.GetComponentsInChildren<Transform>(true))
                        if (t.gameObject.name == "cd(itemy)")
                            t.gameObject.AddComponent<ItemBehaviour>();
            }
        }

19 Source : WheelRepairJobTrigger.cs
with GNU General Public License v3.0
from Athlon007

void Start()
        {
            BoxCollider col = gameObject.AddComponent<BoxCollider>();
            col.isTrigger = true;
            col.size = new Vector3(6, 5, 8);

            StartCoroutine(InitializeRoutine());
        }

19 Source : ItemBehaviour.cs
with GNU General Public License v3.0
from Athlon007

void FsmFixes()
        {
            try
            {
                PlayMakerFSM useFsm = gameObject.GetPlayMakerFSM("Use");
                if (useFsm != null)
                {
                    useFsm.Fsm.RestartOnEnable = false;
                    if (gameObject.name.StartsWith("door ")) return;
                    if (gameObject.name == ("amis-auto ky package(xxxxx)")) return;
                    if (gameObject.name == "lottery ticket(xxxxx)") return;

                    FsmState state1 = useFsm.GetState("State 1");
                    if (state1 != null)
                    {
                        List<FsmStateAction> emptyState1 = state1.Actions.ToList();
                        emptyState1.Insert(0, new CustomStop());
                        state1.Actions = emptyState1.ToArray();
                        state1.SaveActions();
                    }

                    FsmState loadState = useFsm.GetState("Load");
                    if (loadState != null)
                    {
                        List<FsmStateAction> emptyActions = loadState.Actions.ToList();
                        emptyActions.Insert(0, new CustomStop());
                        loadState.Actions = emptyActions.ToArray();
                        loadState.SaveActions();
                    }

                    if (this.gameObject.name == "battery(Clone)")
                    {
                        batteryOnCharged = useFsm.FsmVariables.GetFsmBool("OnCharged");
                    }

                    if (useFsm.FsmVariables.GetFsmFloat("SpoilingRate") != null)
                    {
                        spoilRate = useFsm.FsmVariables.GetFsmFloat("SpoilingRate");
                        condition = useFsm.FsmVariables.GetFsmFloat("Condition");
                    }
                    if (useFsm.FsmVariables.GetFsmFloat("SpoilingRateFridge") != null)
                    {
                        spoilRateFridge = useFsm.FsmVariables.GetFsmFloat("SpoilingRateFridge");
                    }

                    
                }

                // Fixes for particular items.
                switch (gameObject.name)
                {
                    case "diesel(itemx)":
                        transform.Find("FluidTrigger").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "gasoline(itemx)":
                        transform.Find("FluidTrigger").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "motor oil(itemx)":
                        transform.Find("MotorOilTrigger").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "coolant(itemx)":
                        transform.Find("CoolantTrigger").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "brake fluid(itemx)":
                        transform.Find("BrakeFluidTrigger").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "wood carrier(itemx)":
                        transform.Find("WoodTrigger").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "suitcase(itemx)":
                        transform.Find("Money").gameObject.AddComponent<SuitcaseMoneyBehaviour>();
                        break;
                    case "radio(Clone)":
                        if (transform.Find("Channel") != null)
                            transform.Find("Channel").gameObject.AddComponent<RadioDisable>();
                        break;
                    case "fuel tank(Clone)":
                        transform.Find("Bolts").GetChild(7).GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                        break;
                    case "spark plug(Clone)":
                        gameObject.GetPlayMakerFSM("Screw").Fsm.RestartOnEnable = false;
                        break;
                    case "spark plug box(Clone)":
                        break;
                }
                
                PlayMakerFSM dataFsm = gameObject.GetPlayMakerFSM("Data");
                if (dataFsm != null)
                {
                    dataFsm.Fsm.RestartOnEnable = false;
                }

                PlayMakerFSM paintFSM = gameObject.GetPlayMakerFSM("Paint");
                if (paintFSM != null)
                {
                    paintFSM.Fsm.RestartOnEnable = false;
                }
            }
            catch (System.Exception ex)
            {
                ExceptionManager.New(ex, false, $"FSM_FIXES | {gameObject.Path()}");
            }
        }

19 Source : ItemsManager.cs
with GNU General Public License v3.0
from Athlon007

internal void Initialize()
        {
            cashRegisterHook = GameObject.Find("STORE/StoreCashRegister/Register").AddComponent<CashRegisterBehaviour>();

            Transform spawner = GameObject.Find("Spawner").transform;

            InjectSpawnScripts(spawner.Find("CreateItems").gameObject);
            InjectSpawnScripts(spawner.Find("CreateSpraycans").gameObject);
            InjectSpawnScripts(spawner.Find("CreateShoppingbag").gameObject);
            InjectSpawnScripts(spawner.Find("CreateMooseMeat").gameObject);
            InjectSpawnScripts(GameObject.Find("fish trap(itemx)").transform.Find("Spawn").gameObject);

            GetCanTrigger();

            // Car parts order bill hook.
            try
            {
                GameObject storeLOD = GameObject.Find("STORE").transform.Find("LOD").gameObject;
                GameObject activateStore = storeLOD.transform.Find("ActivateStore").gameObject;
                bool lodLastState = storeLOD.activeSelf;
                bool activeStore = activateStore.activeSelf;

                if (!lodLastState)
                    storeLOD.SetActive(true);

                if (!activeStore)
                    activateStore.SetActive(true);

                GameObject postOrder = GameObject.Find("STORE").transform.Find("LOD/ActivateStore/PostOffice/PostOrderBuy").gameObject;
                bool isPostOrderActive = postOrder.activeSelf;
                postOrder.SetActive(true);
                FsmHook.FsmInject(postOrder, "State 3", cashRegisterHook.Packages);
                if (!isPostOrderActive)
                    postOrder.SetActive(false);

                storeLOD.SetActive(lodLastState);
                activateStore.SetActive(activateStore);
            }
            catch
            {
                throw new System.Exception("Couldn't inject PostOrderBuy object.");
            }

            InitializeList();

            // Hooks all bottles and adds adds BeerBottle script to them, which deletes the object and adds the ItemHook to them.
            Dictionary<string, string> names = new Dictionary<string, string>()
            {
                {
                    "BottleBeerFly",
                    "empty bottle(Clone)"
                },
                {
                    "BottleBoozeFly",
                    "empty bottle(Clone)"
                },
                {
                    "BottleSpiritFly",
                    "empty bottle(Clone)"
                },
                {
                    "CoffeeFly",
                    "empty cup(Clone)"
                },
                {
                    "MilkFly",
                    "empty pack(Clone)"
                },
                {
                    "VodkaShotFly",
                    "empty glreplaced(Clone)"
                }
            };
            foreach (GameObject gameObject in Resources.FindObjectsOfTypeAll<GameObject>().Where(obj => names.ContainsKey(obj.name) && obj.GetComponent<PlayMakerFSM>() != null))
            {
                gameObject.AddComponent<ThrowableJunkBehaviour>();
            }

            // Hook the prefab of firewood.
            GameObject firewoodPrefab = Resources.FindObjectsOfTypeAll<GameObject>().FirstOrDefault(f => f.name.EqualsAny("firewood") && f.GetComponent<PlayMakerFSM>() == null).gameObject;
            if (firewoodPrefab)
            {
                firewoodPrefab.AddComponent<ItemBehaviour>();
            }

            // Hook the prefab of log.
            GameObject logPrefab = Resources.FindObjectsOfTypeAll<GameObject>().FirstOrDefault(f => f.name.EqualsAny("log") && f.GetComponent<PlayMakerFSM>() == null).gameObject;
            if (logPrefab)
            {
                logPrefab.AddComponent<ItemBehaviour>();
                logPrefab.transform.Find("log(Clone)").gameObject.AddComponent<ItemBehaviour>();
            }

            foreach (var f in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name == "log(Clone)"))
            {
                f.AddComponent<ItemBehaviour>();
            }

            radiatorHose3Database = GameObject.Find("Database/DatabaseMechanics/RadiatorHose3").GetPlayMakerFSM("Data");
            GameObject attachedHose = Resources.FindObjectsOfTypeAll<GameObject>().First(g => g.name == "radiator hose3(xxxxx)");
            realRadiatorHose = Resources.FindObjectsOfTypeAll<GameObject>().First(g => g.name == "radiator hose3(Clone)");
            GameObject dummy = GameObject.Instantiate(realRadiatorHose); // used for spawning the radiator hose3 after it gets detached.

            UnityEngine.Object.Destroy(dummy.GetComponent<ItemBehaviour>());
            dummy.SetActive(false);
            dummy.name = dummy.name.Replace("(Clone)(Clone)", "(Clone)");

            Transform t = SaveManager.GetRadiatorHose3Transform();

            if (!attachedHose.activeSelf)
            {
                realRadiatorHose.transform.position = t.position;
                realRadiatorHose.transform.rotation = t.rotation;
                realRadiatorHose.SetActive(true);
            }
            radiatorHose3Database.FsmVariables.GameObjectVariables.First(g => g.Name == "SpawnThis").Value = realRadiatorHose;
        }

19 Source : ItemsManager.cs
with GNU General Public License v3.0
from Athlon007

void InitializeList()
        {
            // Find shopping bags in the list
            GameObject[] items = UnityEngine.Object.FindObjectsOfType<GameObject>()
                                .Where(gm => gm.name.ContainsAny(NameList) && gm.name.ContainsAny("(itemx)", "(Clone)") & gm.GetComponent<ItemBehaviour>() == null)
                                .ToArray();

            if (items.Length > 0)
            {
                for (int i = 0; i < items.Length; i++)
                {
                    if (items[i] == null) continue;

                    try
                    {
                        items[i].AddComponent<ItemBehaviour>();
                    }
                    catch { }
                }
            }

            // CD Player Enhanced compatibility
            if (ModLoader.GetMod("CDPlayer") != null)
            {
                GameObject[] cdEnchancedObjects = Resources.FindObjectsOfTypeAll<GameObject>()
                .Where(gm => gm.name.ContainsAny("cd case(itemy)", "CD Rack(itemy)", "cd(itemy)") && gm.activeSelf).ToArray();

                for (int i = 0; i < cdEnchancedObjects.Length; i++)
                {
                    cdEnchancedObjects[i].AddComponent<ItemBehaviour>();
                }

                // Create shop table check, for when the CDs are bought
                GameObject itemCheck = new GameObject("MOP_ItemAreaCheck");
                itemCheck.transform.localPosition = new Vector3(-1551.303f, 4.883998f, 1182.904f);
                itemCheck.transform.localEulerAngles = new Vector3(0f, 58.00043f, 0f);
                itemCheck.transform.localScale = new Vector3(1f, 1f, 1f);
                itemCheck.AddComponent<ShopModItemSpawnCheck>();
            }
            else
            {
                foreach (GameObject cd in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name.ContainsAny("cd case(item", "cd(item")).ToArray())
                    cd.AddComponent<ItemBehaviour>();
            }

            // Get items from ITEMS object.
            GameObject itemsObject = GameObject.Find("ITEMS");
            for (int i = 0; i < itemsObject.transform.childCount; i++)
            {
                GameObject item = itemsObject.transform.GetChild(i).gameObject;
                if (item.name == "CDs") continue;

                try
                {
                    if (item.GetComponent<ItemBehaviour>() != null)
                        continue;

                    item.AddComponent<ItemBehaviour>();
                }
                catch (System.Exception ex)
                {
                    ExceptionManager.New(ex, false, "ITEM_LIST_AT_ITEMS_LOAD_ERROR");
                }
            }

            // Also disable the restart for that sunnuva replaced.
            itemsObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;

            // replaced wheels.
            foreach (GameObject wheel in UnityEngine.Object.FindObjectsOfType<GameObject>().Where(gm => gm.name.EqualsAny("wheel_regula", "wheel_offset") && gm.activeSelf).ToArray())
                wheel.AddComponent<ItemBehaviour>();

            // Tires trigger at Fleetari's.
            GameObject wheelTrigger = new GameObject("MOP_WheelTrigger");
            wheelTrigger.transform.localPosition = new Vector3(1555.49f, 4.8f, 737);
            wheelTrigger.transform.localEulerAngles = new Vector3(1.16f, 335, 1.16f);
            wheelTrigger.AddComponent<WheelRepairJobTrigger>();

            // Hook up the envelope.
            foreach (var g in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name.EqualsAny("envelope(xxxxx)", "lottery ticket(xxxxx)")).ToArray())
                g.AddComponent<ItemBehaviour>();

            // Unparent all childs of CDs object.
            Transform cds = GameObject.Find("ITEMS").transform.Find("CDs");
            if (cds)
            {
                for (int i = 0; i < cds.childCount; i++)
                    cds.GetChild(i).parent = null;
            }
        }

19 Source : SatsumaTriggerFixer.cs
with GNU General Public License v3.0
from Athlon007

void Awake()
        {
            instance = this;

            Transform body = VehicleManager.Instance.GetVehicle(VehiclesTypes.Satsuma).transform.Find("Body");
            foreach (var t in body.GetComponentsInChildren<Transform>(true).Where(g => g.gameObject.name.StartsWith("trigger_")))
            {
                t.gameObject.AddComponent<SatsumaTrigger>();
            }

            Transform block = GameObject.Find("block(Clone)").transform;
            foreach (var t in block.GetComponentsInChildren<Transform>().Where(g => g.gameObject.name.StartsWith("trigger_")))
            {
                t.gameObject.AddComponent<SatsumaTrigger>();
            }
        }

19 Source : Vehicle.cs
with GNU General Public License v3.0
from Athlon007

public void Freeze()
        {
            gameObject.AddComponent<ItemFreezer>();
        }

19 Source : GameFixes.cs
with GNU General Public License v3.0
from Athlon007

public void MainFixes()
        {
            // GT Grille resetting fix.
            try
            {
                PlayMakerFSM[] gtGrille = GameObject.Find("grille gt(Clone)").GetComponents<PlayMakerFSM>();
                foreach (var fsm in gtGrille)
                    fsm.Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "GT_GRILLE_ERROR");
            }

            // Random fixes.
            try
            {
                Transform buildings = GameObject.Find("Buildings").transform;

                // Find house of Teimo and detach it from Perajarvi, so it can be loaded and unloaded separately
                GameObject perajarvi = GameObject.Find("PERAJARVI");
                perajarvi.transform.Find("HouseRintama4").parent = buildings;
                // Same for chicken house.
                perajarvi.transform.Find("ChickenHouse").parent = buildings;

                // Chicken house (barn) close to player's house
                buildings.Find("ChickenHouse").parent = null;

                // Fix for church wall. Changing it's parent to NULL, so it will not be loaded or unloaded.
                // It used to be attached to CHURCH gameobject,
                // but the Amis cars (yellow and grey cars) used to end up in the graveyard area.
                GameObject.Find("CHURCHWALL").transform.parent = null;

                // Fix for old house on the way from Perajarvi to Ventti's house (HouseOld5)
                perajarvi.transform.Find("HouseOld5").parent = buildings;

                // Fix for houses behind Teimo's
                perajarvi.transform.Find("HouseRintama3").parent = buildings;
                perajarvi.transform.Find("HouseSmall3").parent = buildings;

                // Perajarvi fixes for multiple objects with the same name.
                // Instead of being the part of Perajarvi, we're changing it to be the part of Buildings.
                Transform[] perajarviChilds = perajarvi.GetComponentsInChildren<Transform>();
                for (int i = 0; i < perajarviChilds.Length; i++)
                {
                    // Fix for disappearing grain processing plant
                    // https://my-summer-car.fandom.com/wiki/Grain_processing_plant
                    if (perajarviChilds[i].gameObject.name.Contains("silo"))
                    {
                        perajarviChilds[i].parent = buildings;
                        continue;
                    }

                    // Fix for Ventti's and Teimo's mailboxes (and pretty much all mailboxes that are inside of Perajarvi)
                    if (perajarviChilds[i].gameObject.name == "MailBox")
                    {
                        perajarviChilds[i].parent = buildings;
                        continue;
                    }

                    // Fix for greenhouses on the road from Perajarvi to Ventti's house
                    if (perajarviChilds[i].name == "Greenhouse")
                    {
                        perajarviChilds[i].parent = buildings;
                        continue;
                    }
                }

                // Fix for floppies at Jokke's new house
                while (perajarvi.transform.Find("TerraceHouse/diskette(itemx)") != null)
                {
                    Transform diskette = perajarvi.transform.Find("TerraceHouse/diskette(itemx)");
                    if (diskette != null && diskette.parent != null)
                        diskette.parent = null;
                }

                // Fix for Jokke's house furnitures clipping through floor
                perajarvi.transform.Find("TerraceHouse/Colliders").parent = null;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "PERAJARVI_FIXES_ERROR");
            }

            // Fix for cottage items disappearing when moved
            try
            {
                GameObject.Find("coffee pan(itemx)").transform.parent = null;
                GameObject.Find("lantern(itemx)").transform.parent = null;
                GameObject.Find("coffee cup(itemx)").transform.parent = null;
                GameObject.Find("camera(itemx)").transform.parent = null;
                GameObject.Find("COTTAGE/ax(itemx)").transform.parent = null;

                GameObject.Find("fireworks bag(itemx)").transform.parent = null;

                // Fix for fishing areas
                GameObject.Find("FishAreaAVERAGE").transform.parent = null;
                GameObject.Find("FishAreaBAD").transform.parent = null;
                GameObject.Find("FishAreaGOOD").transform.parent = null;
                GameObject.Find("FishAreaGOOD2").transform.parent = null;

                // Fix for strawberry field mailboxes
                GameObject.Find("StrawberryField").transform.Find("LOD/MailBox").parent = null;
                GameObject.Find("StrawberryField").transform.Find("LOD/MailBox").parent = null;

                // Fix for items left on cottage chimney clipping through it on first load of cottage
                GameObject.Find("COTTAGE").transform.Find("MESH/Cottage_chimney").parent = null;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "ITEMS_FIXES_ERROR");
            }

            // Applying a script to vehicles that can pick up and drive the player as a preplacedanger to his house.
            // This script makes it so when the player enters the car, the parent of the vehicle is set to null.
            try
            {
                GameObject fittan = GameObject.Find("TRAFFIC").transform.Find("VehiclesDirtRoad/Rally/FITTAN").gameObject;
                GameObject kuski = GameObject.Find("NPC_CARS").transform.Find("KUSKI").gameObject;
                FsmHook.FsmInject(fittan.transform.Find("PlayerTrigger/DriveTrigger").gameObject, "Player in car", () => fittan.transform.parent = null);
                FsmHook.FsmInject(kuski.transform.Find("PlayerTrigger/DriveTrigger").gameObject, "Player in car", () => kuski.transform.parent = null);

            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "TAXI_MANAGERS_ERROR");
            }

            // Fixed Ventii bet resetting to default on cabin load.
            try
            {
                GameObject.Find("CABIN").transform.Find("Cabin/Ventti/Table/GameManager").GetPlayMakerFSM("Use").Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "VENTII_FIX_ERROR");
            }

            // Junk cars - setting Load game to null.
            int junkCarCounter = 1;
            try
            {
                for (junkCarCounter = 1; GameObject.Find($"JunkCar{junkCarCounter}") != null; junkCarCounter++)
                {
                    GameObject junk = GameObject.Find($"JunkCar{junkCarCounter}");
                    junk.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;

                    WorldObjectManager.Instance.Add(junk, DisableOn.Distance);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, $"JUNK_CARS_{junkCarCounter}_ERROR");;
            }

            // Toggle Humans (apart from Farmer and Fighter2).
            try
            {
                GameObject humans = GameObject.Find("HUMANS");
                foreach (Transform t in GameObject.Find("HUMANS").GetComponentsInChildren<Transform>().Where(t => t.parent == humans.transform))
                {
                    if (t.gameObject.name.EqualsAny("HUMANS", "Fighter2", "Farmer", "FighterPub"))
                        continue;

                    WorldObjectManager.Instance.Add(t.gameObject, DisableOn.Distance);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "HUMANS_ERROR");
            }

            // Fixes wasp hives resetting to on load values.
            try
            {
                GameObject[] wasphives = Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name == "WaspHive").ToArray();
                foreach (GameObject wasphive in wasphives)
                {
                    wasphive.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "WASPHIVES_ERROR");
            }

            // Disabling the script that sets the kinematic state of Satsuma to False.
            try
            {
                GameObject hand = GameObject.Find("PLAYER/Pivot/AnimPivot/Camera/FPSCamera/1Hand_replacedemble/Hand");
                PlayMakerFSM pickUp = hand.GetPlayMakerFSM("PickUp");

                pickUp.GetState("Drop part").RemoveAction(0);
                pickUp.GetState("Drop part 2").RemoveAction(0);
                pickUp.GetState("Tool picked").RemoveAction(2);
                pickUp.GetState("Drop tool").RemoveAction(0);
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "SATSUMA_HAND_BS_FIX");
            }

            // Preventing mattres from being disabled.
            try
            {
                Transform mattres = GameObject.Find("DINGONBIISI").transform.Find("mattres");
                if (mattres != null)
                    mattres.parent = null;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "MANSION_MATTRES_ERROR");
            }

            // Item anti clip for cottage.
            try
            {
                GameObject area = new GameObject("MOP_ItemAntiClip");
                area.transform.position = new Vector3(-848.3f, -5.4f, 505.5f);
                area.transform.eulerAngles = new Vector3(0, 343.0013f, 0);
                area.AddComponent<ItemAntiClip>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "ITEM_ANTICLIP_ERROR");
            }

            // Z-fighting fix for wrisreplacedch.
            try
            {
                GameObject player = GameObject.Find("PLAYER");

                if (player)
                {
                    Transform hour = player.transform.Find("Pivot/AnimPivot/Camera/FPSCamera/FPSCamera/Watch/Animate/BreathAnim/WrisreplacedchHand/Clock/Pivot/Hour/hour");
                    if (hour)
                    {
                        hour.GetComponent<Renderer>().material.renderQueue = 3001;
                    }

                    Transform minute = player.transform.Find("Pivot/AnimPivot/Camera/FPSCamera/FPSCamera/Watch/Animate/BreathAnim/WrisreplacedchHand/Clock/Pivot/Minute/minute");
                    if (minute)
                    {
                        minute.GetComponent<Renderer>().material.renderQueue = 3002;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "HANDWATCH_RENDERER_QUEUE_ERROR");
            }

            // Adds roll fix to the bus.
            try
            {
                GameObject bus = GameObject.Find("BUS");
                if (bus)
                {
                    bus.AddComponent<BusRollFix>();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "BUS_ROLL_FIX_ERROR");
            }

            // Fixes bedroom window wrap resetting to default value.
            try
            {
                Transform triggerWindowWrap = GameObject.Find("YARD").transform.Find("Building/BEDROOM1/trigger_window_wrap");
                if (triggerWindowWrap != null)
                    triggerWindowWrap.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "TRIGGER_WINDOW_WRAP_ERROR");
            }

            // Fixes diskette ejecting not wokring.
            try
            {
                Resources.FindObjectsOfTypeAll<GameObject>().First(g => g.name == "TriggerDiskette")
                    .GetPlayMakerFSM("replacedembly").Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "TRIGGER_DISKETTE_ERROR");
            }

            // Fixed computer memory resetting.
            try
            {
                Resources.FindObjectsOfTypeAll<GameObject>().First(g => g.name == "TriggerPlayMode").GetPlayMakerFSM("PlayerTrigger").Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "TRIGGER_DISKETTE_ERROR");
            }

            // Fixes berry picking skill resetting to default.
            try
            {
                GameObject.Find("JOBS").transform.Find("StrawberryField").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "STRAWBERRY_FIELD_FSM");
            }

            // GrandmaHiker fixes.
            try
            {
                GameObject grandmaHiker = GameObject.Find("GrannyHiker");
                if (grandmaHiker)
                {
                    GameObject skeleton = grandmaHiker.transform.Find("Char/skeleton").gameObject;

                    PlayMakerFSM logicFSM = grandmaHiker.GetPlayMakerFSM("Logic");

                    FsmState openDoorFsmState = logicFSM.GetState("Open door");
                    List<FsmStateAction> openDoorActions = openDoorFsmState.Actions.ToList();
                    openDoorActions.Add(new GrandmaHiker(skeleton, false));
                    openDoorFsmState.Actions = openDoorActions.ToArray();

                    FsmState setMreplaced2State = logicFSM.GetState("Set mreplaced 2");
                    List<FsmStateAction> setMreplaced2Actions = setMreplaced2State.Actions.ToList();
                    setMreplaced2Actions.Add(new GrandmaHiker(skeleton, true));
                    setMreplaced2State.Actions = setMreplaced2Actions.ToArray();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "GRANDMA_HIKER_FIXES");
            }

            // Cabin door resetting fix.
            try
            {
                GameObject.Find("CABIN").transform.Find("Cabin/Door/Pivot/Handle").gameObject.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "CABIN_DOOR_RESET_FIX_ERROR");
            }

            // Construction site
            try
            {
                Transform construction = GameObject.Find("PERAJARVI").transform.Find("ConstructionSite");
                if (construction)
                {
                    construction.parent = null;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "PERAJARVI_CONSTRUCTION_ERROR");
            }

            // Satsuma parts trigger fix.
            try
            {
                gameObject.AddComponent<SatsumaTriggerFixer>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "SATSUMA_TRIGGER_FIXER_ERROR");
            }

            // MailBox fix
            try
            {
                foreach (var g in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name == "MailBox"))
                {
                    Transform hatch = g.transform.Find("BoxHatch");
                    if (hatch)
                    {
                        hatch.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "MAILBOX_ERROR");
            }

            ModConsole.Log("[MOP] Finished applying fixes");
        }

19 Source : GameFixes.cs
with GNU General Public License v3.0
from Athlon007

IEnumerator HoodFixCoroutine(Transform hoodPivot, Transform batteryPivot, Transform batteryTrigger)
        {
            yield return new WaitForSeconds(2);

            // Hood
            Transform hood = Resources.FindObjectsOfTypeAll<GameObject>().First(g => g.name == "hood(Clone)").transform;
            CustomPlayMakerFixedUpdate hoodFixedUpdate = hood.gameObject.AddComponent<CustomPlayMakerFixedUpdate>();

            // Fiber Hood
            GameObject fiberHood = Resources.FindObjectsOfTypeAll<GameObject>()
                .First(obj => obj.name == "fiberglreplaced hood(Clone)"
                && obj.GetComponent<PlayMakerFSM>() != null
                && obj.GetComponent<MeshCollider>() != null);

            int retries = 0;
            if (FsmManager.IsStockHoodBolted() && hood.parent != hoodPivot)
            {
                hood.gameObject.SetActive(true);

                while (hood.parent != hoodPivot)
                {
                    // Satsuma got disabled while trying to fix the hood.
                    // Attempt to fix it later.
                    if (!hoodPivot.gameObject.activeSelf)
                    {
                        yield break;
                    }

                    FsmManager.ForceHoodreplacedemble();
                    yield return null;

                    // If 10 retries failed, quit the loop.
                    retries++;
                    if (retries == 10)
                    {
                        break;
                    }
                }
            }

            hoodFixedUpdate.StartFixedUpdate();

            if (fiberHood != null && FsmManager.IsFiberHoodBolted() && fiberHood.transform.parent != hoodPivot)
            {
                retries = 0;
                while (fiberHood.transform.parent != hoodPivot)
                {
                    // Satsuma got disabled while trying to fix the hood.
                    // Attempt to fix it later.
                    if (!hoodPivot.gameObject.activeSelf)
                    {
                        Satsuma.Instance.AfterFirstEnable = false;
                        yield break;
                    }

                    FsmManager.ForceHoodreplacedemble();
                    yield return null;

                    // If 10 retries failed, quit the loop.
                    retries++;
                    if (retries == 60)
                    {
                        break;
                    }
                }
            }

            hood.gameObject.AddComponent<SatsumaBoltsAntiReload>();
            fiberHood.gameObject.AddComponent<SatsumaBoltsAntiReload>();

            // Adds delayed initialization for hood hinge.
            if (hood.gameObject.GetComponent<DelayedHingeManager>() == null)
                hood.gameObject.AddComponent<DelayedHingeManager>();

            // Fix for hood not being able to be closed.
            if (hood.gameObject.GetComponent<SatsumaCustomHoodUse>() == null)
                hood.gameObject.AddComponent<SatsumaCustomHoodUse>();

            // Fix for battery popping out.
            if (FsmManager.IsBatteryInstalled() && batteryPivot.parent == null)
            {
                batteryTrigger.gameObject.SetActive(true);
                batteryTrigger.gameObject.GetComponent<PlayMakerFSM>().SendEvent("replacedEMBLE");
            }

            HoodFixDone = true;
        }

19 Source : Hypervisor.cs
with GNU General Public License v3.0
from Athlon007

void Initialize()
        {
            instance = this;

            ModConsole.Log("[MOP] Loading MOP...");

            // Initialize the worldObjectManager list
            worldObjectManager = new WorldObjectManager();

            // Looking for player and yard
            player = GameObject.Find("PLAYER").transform;

            // Add GameFixes MonoBehaviour.
            try
            {
                gameObject.AddComponent<GameFixes>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, $"GAME_FIXES_INITIALIZAITON | {ex}");
            }

            // Loading vehicles
            vehicleManager = new VehicleManager();

            // World Objects
            try
            {
                worldObjectManager.Add("CABIN", DisableOn.Distance | DisableOn.IgnoreInQualityMode);
                worldObjectManager.Add("COTTAGE", DisableOn.Distance, 400);
                worldObjectManager.Add("DANCEHALL", DisableOn.Distance, 500);
                worldObjectManager.Add("PERAJARVI", DisableOn.Distance | DisableOn.IgnoreInQualityMode, 400);
                worldObjectManager.Add("SOCCER", DisableOn.Distance);
                worldObjectManager.Add("WATERFACILITY", DisableOn.Distance, 300);
                worldObjectManager.Add("DRAGRACE", DisableOn.Distance, 1100);
                worldObjectManager.Add("StrawberryField", DisableOn.Distance, 400);
                worldObjectManager.Add("MAP/Buildings/DINGONBIISI", DisableOn.Distance, 400);
                worldObjectManager.Add("RALLY/PartsSalesman", DisableOn.Distance, 400);
                worldObjectManager.Add("LakeSmallBottom1", DisableOn.Distance, 500);
                worldObjectManager.Add("machine", DisableOn.Distance, 200, silent: true);

                ModConsole.Log("[MOP] World objects (1) loaded");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "WORLD_OBJECTS_1_INITIALIZAITON_FAIL");
            }

            // Initialize places.
            placeManager = new PlaceManager();

            // Fixes
            GameFixes.Instance.MainFixes();

            //Things that should be enabled when out of proximity of the house
            try
            {
                worldObjectManager.Add("NPC_CARS", DisableOn.PlayerInHome);
                worldObjectManager.Add("TRAFFIC", DisableOn.PlayerInHome);
                worldObjectManager.Add("TRAIN", DisableOn.PlayerInHome | DisableOn.IgnoreInQualityMode);
                worldObjectManager.Add("Buildings", DisableOn.PlayerInHome);
                worldObjectManager.Add("TrafficSigns", DisableOn.PlayerInHome);
                worldObjectManager.Add("StreetLights", DisableOn.PlayerInHome);
                worldObjectManager.Add("HUMANS", DisableOn.PlayerInHome);
                worldObjectManager.Add("TRACKFIELD", DisableOn.PlayerInHome);
                worldObjectManager.Add("SkijumpHill", DisableOn.PlayerInHome | DisableOn.IgnoreInQualityMode);
                worldObjectManager.Add("Factory", DisableOn.PlayerInHome);
                worldObjectManager.Add("WHEAT", DisableOn.PlayerInHome);
                worldObjectManager.Add("RAILROAD", DisableOn.PlayerInHome);
                worldObjectManager.Add("AIRPORT", DisableOn.PlayerInHome);
                worldObjectManager.Add("RAILROAD_TUNNEL", DisableOn.PlayerInHome);
                worldObjectManager.Add("PierDancehall", DisableOn.PlayerInHome);
                worldObjectManager.Add("PierRiver", DisableOn.PlayerInHome);
                worldObjectManager.Add("PierStore", DisableOn.PlayerInHome);
                worldObjectManager.Add("BRIDGE_dirt", DisableOn.PlayerInHome);
                worldObjectManager.Add("BRIDGE_highway", DisableOn.PlayerInHome);
                worldObjectManager.Add("BirdTower", DisableOn.Distance, 400);
                worldObjectManager.Add("RYKIPOHJA", DisableOn.PlayerInHome);
                worldObjectManager.Add("COMPUTER", DisableOn.PlayerAwayFromHome);

                ModConsole.Log("[MOP] World objects (2) loaded");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "WORLD_OBJECTS_2_INITIALIZAITON_FAIL");
            }

            // Adding area check if Satsuma is in the inspection's area
            try
            {
                SatsumaInArea inspectionArea = GameObject.Find("INSPECTION").AddComponent<SatsumaInArea>();
                inspectionArea.Initialize(new Vector3(20, 20, 20));
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "SATSUMA_AREA_CHECK_INSPECTION_FAIL");
            }

            // Check for when Satsuma is on the lifter
            try
            {
                SatsumaInArea lifterArea = GameObject.Find("REPAIRSHOP/Lifter/Platform").AddComponent<SatsumaInArea>();
                lifterArea.Initialize(new Vector3(5, 5, 5));
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "SATSUMA_AREA_CHECK_REPAIRSHOP_FAIL");
            }

            // Area for the parc ferme.
            try
            {
                GameObject parcFermeTrigger = new GameObject("MOP_ParcFermeTrigger");
                parcFermeTrigger.transform.parent = GameObject.Find("RALLY").transform.Find("Scenery");
                parcFermeTrigger.transform.position = new Vector3(-1383f, 3f, 1260f);
                SatsumaInArea parcFerme = parcFermeTrigger.AddComponent<SatsumaInArea>();
                parcFerme.Initialize(new Vector3(41, 12, 35));
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "PARC_FERME_TRIGGER_FAIL");
            }

            ModConsole.Log("[MOP] Satsuma triggers loaded");

            // Jokke's furnitures.
            // Only renderers are going to be toggled.
            try
            {
                if (GameObject.Find("tv(Clo01)"))
                {
                    string[] furnitures = { "tv(Clo01)", "chair(Clo02)", "chair(Clo05)", "bench(Clo01)",
                                            "bench(Clo02)", "table(Clo02)", "table(Clo03)", "table(Clo04)",
                                            "table(Clo05)", "desk(Clo01)", "arm chair(Clo01)" };

                    foreach (string furniture in furnitures)
                    {
                        GameObject g = GameObject.Find(furniture);
                        if (g)
                        {
                            g.transform.parent = null;
                            worldObjectManager.Add(g, DisableOn.Distance, 100, ToggleModes.Renderer);
                        }
                    }

                    ModConsole.Log("[MOP] Jokke's furnitures found and loaded");
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "JOKKE_FURNITURE_ERROR");
            }

            // Haybales.
            // First we null out the prevent it from reloading the position of haybales.
            try
            {
                GameObject haybalesParent = GameObject.Find("JOBS/HayBales");
                if (haybalesParent != null)
                {
                    haybalesParent.GetComponent<PlayMakerFSM>().Fsm.RestartOnEnable = false;
                    // And now we add all child haybale to world objects.
                    foreach (Transform haybale in haybalesParent.transform.GetComponentInChildren<Transform>())
                    {
                        worldObjectManager.Add(haybale.gameObject.name, DisableOn.Distance | DisableOn.IgnoreInQualityMode, 120);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "HAYBALES_FIX_ERROR");
            }

            // Logwalls
            try
            {
                foreach (GameObject wall in Resources.FindObjectsOfTypeAll<GameObject>().Where(g => g.name == "LogwallLarge"))
                    worldObjectManager.Add(wall, DisableOn.Distance, 300);
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "LOGWALL_LOAD_ERROR");
            }

            // Perajarvi Church.
            try
            {
                if (MopSettings.Mode != PerformanceMode.Performance)
                {
                    GameObject church = GameObject.Find("PERAJARVI").transform.Find("CHURCH").gameObject;
                    church.transform.parent = null;
                    GameObject churchLOD = church.transform.Find("LOD").gameObject;
                    church.GetComponent<PlayMakerFSM>().enabled = false;
                    worldObjectManager.Add(churchLOD, DisableOn.Distance, 300);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "CHURCH_LOD_ERROR");
            }

            // Lake houses.
            try
            {
                if (MopSettings.Mode == PerformanceMode.Quality)
                {
                    GameObject.Find("PERAJARVI").transform.Find("TerraceHouse").transform.parent = null;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "LAKE_HOUSE_ERROR");
            }

            // VehiclesHighway renderers.
            try
            {
                Transform vehiclesHighway = GameObject.Find("TRAFFIC").transform.Find("VehiclesHighway");
                foreach (var f in vehiclesHighway.GetComponentsInChildren<Transform>(true).Where(f => f.parent == vehiclesHighway))
                {
                    worldObjectManager.Add(f.gameObject, DisableOn.Distance, 600, ToggleModes.MultipleRenderers);
                }

                // Also we gonna fix the lag on initial traffic load.
                vehiclesHighway.gameObject.SetActive(true);
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "TRAFFIC_VEHICLES_ERROR");
            }

            // FITTAN renderers.
            try
            {
                worldObjectManager.Add(GameObject.Find("TRAFFIC").transform.Find("VehiclesDirtRoad/Rally/FITTAN").gameObject, DisableOn.Distance, 600, ToggleModes.MultipleRenderers);
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "FITTAN_RENDERERS_ERROR");
            }

            // Initialize Items clreplaced
            try
            {
                new ItemsManager();
                ItemsManager.Instance.Initialize();
                ModConsole.Log("[MOP] Items clreplaced initialized");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "ITEMS_CLreplaced_ERROR");
            }

            try
            {
                DateTime now = DateTime.Now;
                if (now.Day == 1 && now.Month == 4)
                {
                    GameObject fpsObject = GameObject.Find("GUI").transform.Find("HUD/FPS/HUDValue").gameObject;
                    PlayMakerFSM[] fsms = fpsObject.GetComponents<PlayMakerFSM>();
                    foreach (var fsm in fsms)
                        fsm.enabled = false;
                    fpsObject.GetComponent<TextMesh>().text = "99999999 :)";
                    fpsObject.transform.Find("HUDValueShadow").GetComponent<TextMesh>().text = "99999999 :)";
                }
            }
            catch { }

            HookPreSaveGame();

            ModConsole.Log("[MOP] Loading rules...");
            foreach (ToggleRule v in RulesManager.Instance.ToggleRules)
            {
                try
                {
                    switch (v.ToggleMode)
                    {
                        default:
                            ModConsole.LogError($"[MOP] Unrecognized toggle mode for {v.ObjectName}: {v.ToggleMode}.");
                            break;
                        case ToggleModes.Simple:
                            if (GameObject.Find(v.ObjectName) == null)
                            {
                                ModConsole.LogError($"[MOP] Couldn't find world object {v.ObjectName}");
                                continue;
                            }

                            worldObjectManager.Add(v.ObjectName, DisableOn.Distance);
                            break;
                        case ToggleModes.Renderer:
                            if (GameObject.Find(v.ObjectName) == null)
                            {
                                ModConsole.LogError($"[MOP] Couldn't find world object {v.ObjectName}");
                                continue;
                            }

                            worldObjectManager.Add(v.ObjectName, DisableOn.Distance, 200, ToggleModes.Renderer);
                            break;
                        case ToggleModes.Item:
                            GameObject g = GameObject.Find(v.ObjectName);

                            if (g == null)
                            {
                                ModConsole.LogError($"[MOP] Couldn't find item {v.ObjectName}");
                                continue;
                            }

                            if (g.GetComponent<ItemBehaviour>() == null)
                                g.AddComponent<ItemBehaviour>();
                            break;
                        case ToggleModes.Vehicle:
                            if (RulesManager.Instance.SpecialRules.IgnoreModVehicles) continue;

                            if (GameObject.Find(v.ObjectName) == null)
                            {
                                ModConsole.LogError($"[MOP] Couldn't find vehicle {v.ObjectName}");
                                continue;
                            }

                            vehicleManager.Add(new Vehicle(v.ObjectName));
                            break;
                        case ToggleModes.VehiclePhysics:
                            if (RulesManager.Instance.SpecialRules.IgnoreModVehicles) continue;

                            if (GameObject.Find(v.ObjectName) == null)
                            {
                                ModConsole.LogError($"[MOP] Couldn't find vehicle {v.ObjectName}");
                                continue;
                            }
                            vehicleManager.Add(new Vehicle(v.ObjectName));
                            Vehicle veh = vehicleManager[vehicleManager.Count - 1];
                            veh.Toggle = veh.ToggleUnityCar;
                            break;
                    }
                }
                catch (Exception ex)
                {
                    ExceptionManager.New(ex, false, "TOGGLE_RULES_LOAD_ERROR");
                }
            }

            ModConsole.Log("[MOP] Rules loading complete!");

            // Initialzie sector manager
            try
            {
                gameObject.AddComponent<SectorManager>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "SECTOR_MANAGER_ERROR");
            }

            // Add DynamicDrawDistance component.
            try
            {
                gameObject.AddComponent<DynamicDrawDistance>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "DYNAMIC_DRAW_DISTANCE_ERROR");
            }

            if (MopSettings.Mode != PerformanceMode.Safe)
                ToggleAll(false, ToggleAllMode.OnLoad);

            // Initialize the coroutines.
            currentLoop = LoopRoutine();
            StartCoroutine(currentLoop);
            currentControlCoroutine = ControlCoroutine();
            StartCoroutine(currentControlCoroutine);

            ModConsole.Log("<color=green>[MOP] MOD LOADED SUCCESFULLY!</color>");
            Resources.UnloadUnusedreplacedets();
            GC.Collect();

            // If generate-list command is set to true, generate the list of items that are disabled by MOP.
            if (MopSettings.GenerateToggledItemsListDebug)
            {
                if (System.IO.File.Exists("world.txt"))
                    System.IO.File.Delete("world.txt");
                string world = "";
                foreach (var w in worldObjectManager.GetList())
                {
                    if (world.Contains(w.GetName())) continue;
                    world += w.GetName() + ", ";
                }
                System.IO.File.WriteAllText("world.txt", world);
                System.Diagnostics.Process.Start("world.txt");

                if (System.IO.File.Exists("vehicle.txt"))
                    System.IO.File.Delete("vehicle.txt");
                string vehiclez = "";
                foreach (var w in vehicleManager.List())
                    vehiclez += w.gameObject.name + ", ";
                System.IO.File.WriteAllText("vehicle.txt", vehiclez);
                System.Diagnostics.Process.Start("vehicle.txt");

                if (System.IO.File.Exists("items.txt"))
                    System.IO.File.Delete("items.txt");
                string items = "";
                foreach (var w in ItemsManager.Instance.All())
                {
                    if (items.Contains(w.gameObject.name)) continue;
                    items += w.gameObject.name + ", ";
                }
                System.IO.File.WriteAllText("items.txt", items);
                System.Diagnostics.Process.Start("items.txt");

                if (System.IO.File.Exists("place.txt"))
                    System.IO.File.Delete("place.txt");
                string place = "";
                foreach (var w in placeManager.GetList())
                {
                    place += w.GetName() + ": ";
                    foreach (var f in w.GetDisableableChilds())
                    {
                        if (place.Contains(f.gameObject.name)) continue;
                        place += f.gameObject.name + ", ";
                    }

                    place += "\n\n";
                }
                System.IO.File.WriteAllText("place.txt", place);
                System.Diagnostics.Process.Start("place.txt");
            }
        }

19 Source : Hypervisor.cs
with GNU General Public License v3.0
from Athlon007

void HookPreSaveGame()
        {
            try
            {
            GameObject[] saveGames = Resources.FindObjectsOfTypeAll<GameObject>()
                .Where(obj => obj.name.Contains("SAVEGAME")).ToArray();

                int i = 0;
                for (; i < saveGames.Length; i++)
                {
                    bool useInnactiveFix = false;
                    bool isJail = false;

                    if (!saveGames[i].activeSelf)
                    {
                        useInnactiveFix = true;
                        saveGames[i].SetActive(true);
                    }

                    if (saveGames[i].transform.parent != null && saveGames[i].transform.parent.name == "JAIL" && saveGames[i].transform.parent.gameObject.activeSelf == false)
                    {
                        useInnactiveFix = true;
                        isJail = true;
                        saveGames[i].transform.parent.gameObject.SetActive(true);
                    }

                    FsmHook.FsmInject(saveGames[i], "Mute audio", PreSaveGame);

                    if (useInnactiveFix)
                    {
                        if (isJail)
                        {
                            saveGames[i].transform.parent.gameObject.SetActive(false);
                            continue;
                        }

                        saveGames[i].SetActive(false);
                    }
                }

                // Hooking up on death save.
                GameObject onDeathSaveObject = new GameObject("MOP_OnDeathSave");
                onDeathSaveObject.transform.parent = GameObject.Find("Systems").transform.Find("Death/GameOverScreen");
                OnDeathBehaviour behaviour = onDeathSaveObject.AddComponent<OnDeathBehaviour>();
                behaviour.Initialize(PreSaveGame);
                i++;

                // Adding custom action to state that will trigger PreSaveGame, if the player picks up the phone with large Suski.
                PlayMakerFSM useHandleFSM = GameObject.Find("Telephone").transform.Find("Logic/UseHandle").GetComponent<PlayMakerFSM>();
                FsmState phoneFlip = useHandleFSM.GetState("Pick phone");
                List<FsmStateAction> phoneFlipActions = phoneFlip.Actions.ToList();
                phoneFlipActions.Insert(0, new CustomSuskiLargeFlip());
                phoneFlip.Actions = phoneFlipActions.ToArray();
                i++;

                ModConsole.Log($"[MOP] Hooked {i} save points!");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "SAVE_HOOK_ERROR");
            }
        }

19 Source : Hypervisor.cs
with GNU General Public License v3.0
from Athlon007

IEnumerator LoopRoutine()
        {
            MopSettings.IsModActive = true;

            FramerateRecorder rec = gameObject.AddComponent<FramerateRecorder>();
            rec.Initialize();

            while (MopSettings.IsModActive)
            {
                // Ticks make sure that MOP is still up and running.
                // If the ticks didn't update, that means this routine stopped.
                ++ticks;

                if (!itemInitializationDelayDone)
                {
                    // We are slightly delaying the initialization, so all items have chance to set in place, because replaced MSC and its physics.
                    waitTime++;
                    if (waitTime >= WaitDone)
                    {
                        FinishLoading();
                    }
                }

                isPlayerAtYard = MOP.ActiveDistance.Value == 0 ? Vector3.Distance(player.position, placeManager[0].transform.position) < 100
                    : Vector3.Distance(player.position, placeManager[0].transform.position) < 100 * MopSettings.ActiveDistanceMultiplicationValue;

                // When player is in any of the sectors, MOP will act like the player is at yard.
                if (SectorManager.Instance.IsPlayerInSector())
                {
                    inSectorMode = true;
                    isPlayerAtYard = true;
                }
                else
                {
                    inSectorMode = false;
                }

                yield return null;

                int i;
                long half = worldObjectManager.Count >> 1;
                // World Objects.
                for (i = 0; i < worldObjectManager.Count; ++i)
                {
                    if (i == half)
                        yield return null;

                    try
                    {
                        GenericObject worldObject = worldObjectManager[i];

                        // Check if object was destroyed (mostly intended for AI pedastrians).
                        if (worldObject.GameObject == null)
                        {
                            worldObjectManager.Remove(worldObject);
                            continue;
                        }

                        if (SectorManager.Instance.IsPlayerInSector() && SectorManager.Instance.SectorRulesContains(worldObject.GameObject.name))
                        {
                            worldObject.GameObject.SetActive(true);
                            continue;
                        }

                        // Should the object be disabled when the player leaves the house?
                        if (worldObject.DisableOn.HasFlag(DisableOn.PlayerAwayFromHome) || worldObject.DisableOn.HasFlag(DisableOn.PlayerInHome))
                        {
                            if (worldObject.GameObject.name == "NPC_CARS" && inSectorMode)
                                continue;

                            if (worldObject.GameObject.name == "COMPUTER" && worldObject.GameObject.transform.Find("SYSTEM").gameObject.activeSelf)
                                continue;

                            worldObject.Toggle(worldObject.DisableOn.HasFlag(DisableOn.PlayerAwayFromHome) ? isPlayerAtYard : !isPlayerAtYard);
                        }
                        else if (worldObject.DisableOn.HasFlag(DisableOn.Distance))
                        {
                            // The object will be disabled, if the player is in the range of that object.
                            worldObject.Toggle(IsEnabled(worldObject.transform, worldObject.Distance));
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, "WORLD_OBJECT_TOGGLE_ERROR");
                    }
                }

                // Safe mode prevents toggling elemenets that MAY case some issues (vehicles, items, etc.)
                if (MopSettings.Mode == PerformanceMode.Safe)
                {
                    yield return new WaitForSeconds(.7f);
                    continue;
                }

                // So we create two separate lists - one is meant to enable, and second is ment to disable them,
                // Why?
                // If we enable items before enabling vehicle inside of which these items are supposed to be, they'll fall through to ground.
                // And the opposite happens if we disable vehicles before disabling items.
                // So if we are disabling items, we need to do that BEFORE we disable vehicles.
                // And we need to enable items AFTER we enable vehicles.
                itemsToEnable.Clear();
                itemsToDisable.Clear();
                half = ItemsManager.Instance.Count >> 1;
                for (i = 0; i < ItemsManager.Instance.Count; ++i)
                {
                    if (i == half)
                        yield return null;

                    // Safe check if somehow the i gets bigger than array length.
                    if (i >= ItemsManager.Instance.Count) break;

                    try
                    {

                        ItemBehaviour item = ItemsManager.Instance[i];

                        if (item == null || item.gameObject == null)
                        {
                            itemsToRemove.Add(item);
                            continue;
                        }

                        // Check the mode in what MOP is supposed to run and adjust to it.
                        bool toEnable = true;
                        if (MopSettings.Mode == 0)
                            toEnable = IsEnabled(item.transform, FsmManager.IsPlayerInCar() && !isPlayerAtYard ? 20 : 150);
                        else
                            toEnable = IsEnabled(item.transform, 150);

                        if (toEnable)
                        {
                            item.ToggleChangeFix();
                            if (item.ActiveSelf) continue;
                            itemsToEnable.Add(item);
                        }
                        else
                        {
                            if (!item.ActiveSelf) continue;
                            itemsToDisable.Add(item);
                        }

                        if (item.rb != null && item.rb.IsSleeping())
                        {
                            if (item.IsPartMagnetAttached()) continue;
                            if (CompatibilityManager.IsInBackpack(item)) continue;
                            item.rb.isKinematic = true;
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, "ITEM_TOGGLE_GATHER_ERROR");
                    }
                }

                // Items To Disable
                int full = itemsToDisable.Count;
                if (full > 0)
                {
                    half = itemsToDisable.Count >> 1;
                    for (i = 0; i < full; ++i)
                    {
                        if (half != 0 && i == half)
                            yield return null;

                        try
                        {
                            itemsToDisable[i].Toggle(false);
                        }
                        catch (Exception ex)
                        {
                            ExceptionManager.New(ex, false, "ITEM_TOGGLE_DISABLE_ERROR - " + itemsToDisable[i] != null ? itemsToDisable[i].gameObject.name : "null");
                        }
                    }
                }

                // Vehicles (new)
                half = vehicleManager.Count >> 1;
                for (i = 0; i < vehicleManager.Count; ++i)
                {
                    if (half != 0 && i == half) yield return null;

                    try
                    {
                        if (vehicleManager[i] == null)
                        {
                            vehicleManager.RemoveAt(i);
                            continue;
                        }

                        float distance = Vector3.Distance(player.transform.position, vehicleManager[i].transform.position);
                        float toggleDistance = MOP.ActiveDistance.Value == 0
                            ? MopSettings.UnityCarActiveDistance : MopSettings.UnityCarActiveDistance * MopSettings.ActiveDistanceMultiplicationValue;

                        switch (vehicleManager[i].VehicleType)
                        {
                            case VehiclesTypes.Satsuma:
                                Satsuma.Instance.ToggleElements(distance);
                                vehicleManager[i].ToggleEventSounds(distance < 3);
                                break;
                            case VehiclesTypes.Jonnez:
                                vehicleManager[i].ToggleEventSounds(distance < 2);
                                break;
                        }

                        vehicleManager[i].ToggleUnityCar(IsVehiclePhysicsEnabled(distance, toggleDistance));
                        vehicleManager[i].Toggle(IsVehicleEnabled(distance));
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, $"VEHICLE_TOGGLE_ERROR_{i}");
                    }
                }

                // Items To Enable
                full = itemsToEnable.Count;
                if (full > 0)
                {
                    half = full >> 1;
                    for (i = 0; i < full; ++i)
                    {
                        if (half != 0 && i == half) yield return null;

                        try
                        {
                            itemsToEnable[i].Toggle(true);
                        }
                        catch (Exception ex)
                        {
                            ExceptionManager.New(ex, false, "ITEM_TOGGLE_ENABLE_ERROR - " + itemsToEnable[i] != null ? itemsToDisable[i].gameObject.name : "null");
                        }
                    }
                }

                // Places (New)
                full = placeManager.Count;
                half = full >> 1;
                for (i = 0; i < full; ++i)
                {
                    if (i == half)
                        yield return null;

                    try
                    {
                        if (SectorManager.Instance.IsPlayerInSector() && SectorManager.Instance.SectorRulesContains(placeManager[i].GetName()))
                        {
                            continue;
                        }

                        placeManager[i].ToggleActive(IsPlaceEnabled(placeManager[i].transform, placeManager[i].GetToggleDistance()));
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, $"PLACE_TOGGLE_ERROR_{i}");
                    }
                }

                // Remove items that don't exist anymore.
                if (itemsToRemove.Count > 0)
                {
                    for (i = itemsToRemove.Count - 1; i >= 0; --i)
                    {
                        ItemsManager.Instance.RemoveAt(i);
                    }

                    itemsToRemove.Clear();
                }

                yield return new WaitForSeconds(.7f);

                if (retries > 0 && !restartSucceedMessaged)
                {
                    restartSucceedMessaged = true;
                    ModConsole.Log("<color=green>[MOP] Restart succeeded!</color>");
                }
            }
        }

19 Source : BugReporter.cs
with GNU General Public License v3.0
from Athlon007

IEnumerator CheckSaveSlots()
        {
            yield return null;

            if (GameObject.Find("SaveSlotsCanvas(Clone)") != null)
            {
                GameObject.Find("SaveSlotsCanvas(Clone)").transform.Find("SaveSlotsUI/Saves/SavesList").gameObject.AddComponent<SaveSlotsSupport>();
            }
        }

19 Source : CustomAddItemBehaviour.cs
with GNU General Public License v3.0
from Athlon007

IEnumerator DelayAdd()
        {
            for (int i = 0; i < 60; ++i)
                yield return null;
            gameObject.AddComponent<ItemBehaviour>();
            Destroy(this);
        }

19 Source : CustomCreateObject.cs
with GNU General Public License v3.0
from Athlon007

public override void OnEnter()
        {
            newObject = GameObject.Instantiate(prefab);
            newObject.transform.position = parent.transform.position;
            newObject.name = newObject.name.Replace("(Clone)(Clone)", "(Clone)");
            newObject.SetActive(true);
            newObject.AddComponent<ItemBehaviour>();
        }

19 Source : ThrowableJunkBehaviour.cs
with GNU General Public License v3.0
from Athlon007

void Start()
        {
            if (MOP.DestroyEmptyBottles.Value)
            {
                Destroy(gameObject);
                return;
            }

            gameObject.AddComponent<ItemBehaviour>();

            this.enabled = false;
        }

19 Source : ItemBehaviour.cs
with GNU General Public License v3.0
from Athlon007

public void Freeze()
        {
            // If the item is an Kilju or Empty Plastic Can, and is close to the CanTrigger object,
            // teleport the object to LostSpawner (junk yard).
            ResetKiljuContainer();

            gameObject.AddComponent<ItemFreezer>();
        }

19 Source : RulesManager.cs
with GNU General Public License v3.0
from Athlon007

public void WipeAll(bool overrideUpdateCheck)
        {
            ResetLists();

            // Destroy old rule files loader object, if it exists.
            GameObject oldRuleFilesLoader = GameObject.Find("MOP_RuleFilesLoader");
            if (oldRuleFilesLoader != null)
                Object.Destroy(oldRuleFilesLoader);

            GameObject ruleFileDownloader = new GameObject("MOP_RuleFilesLoader");
            Loader ruleFilesLoader = ruleFileDownloader.AddComponent<Loader>();
            ruleFilesLoader.Initialize(overrideUpdateCheck);
        }

19 Source : MOP.cs
with GNU General Public License v3.0
from Athlon007

public override void PostLoad()
        {
            MopSettings.UpdateFramerateLimiter();
            MopSettings.UpdatePerformanceMode();
            MopSettings.UpdateShadows();
            MopSettings.UpdateMiscSettings();
            if (MopSettings.IsConfilctingModPresent(out string modName))
            {
                ModConsole.LogError("MOP could not be loaded, because the following mod is present: " + modName);
                return;
            }

            // Create WorldManager game object
            GameObject worldManager = new GameObject("MOP");

            // Initialize CompatibiliyManager
            new CompatibilityManager();

            // Add WorldManager clreplaced
            worldManager.AddComponent<Hypervisor>();

            SaveManager.AddSaveFlag();
        }

19 Source : SatsumaInArea.cs
with GNU General Public License v3.0
from Athlon007

public void Initialize(Vector3 size)
        {
            referenceObject = Satsuma.Instance.GetCarBody();
            collider = gameObject.AddComponent<BoxCollider>();
            collider.isTrigger = true;
            collider.size = size;
            collider.transform.position = transform.position;

            isParcFerme = this.gameObject.name == "MOP_ParcFermeTrigger";
        }

19 Source : MOP.cs
with GNU General Public License v3.0
from Athlon007

public override void MenuOnLoad()
        {
            modSettings.LoadSettings();
            modConfigPath = ModLoader.GetModSettingsFolder(this, true);
            if (!Version.StartsWith(lastVersion.Value.ToString()))
            {
                lastVersion.Value = Version;
                modSettings.SaveSettings();
                ModPrompt.CreatePrompt($"Welcome to Modern Optimization Plugin <color=yellow>{Version}</color>!\n\n" +
                    $"Please consider supporting the project using <color=#3687D7>PayPal</color>,\n" +
                    $"or with <color=#ADAD46>Bitcoins</color>.", "MOP");
            }

            FsmManager.ResetAll();
            Resources.UnloadUnusedreplacedets();
            GC.Collect();

            GameObject bugReporter = new GameObject("MOP_BugReporter");
            bugReporter.AddComponent<BugReporter>();

            MopSettings.Restarts++;
            if (MopSettings.Restarts > MopSettings.MaxRestarts && !MopSettings.RestartWarningShown)
            {
                MopSettings.RestartWarningShown = true;
                ModPrompt prompt = ModPrompt.CreateCustomPrompt();
                prompt.Text = "You've reloaded game without fully quitting it over 5 times.\n\n" +
                                       "It is recommended to fully quit the game after a while, so it would fully unload the memory.\n" +
                                       "Not doing that may lead to game breaking glitches.";
                prompt.replacedle = "MOP";
                prompt.AddButton("OK", null);
                prompt.AddButton("QUIT GAME", () => Application.Quit());
            }

            if (MopSettings.AttemptedToFixTheGame && !MopSettings.AttemptedToFixTheGameRestart)
            {
                MopSettings.AttemptedToFixTheGameRestart = true;
                BugReporter.Instance.RestartGame();
                return;
            }
            MopSettings.AttemptedToFixTheGame = false;
            MopSettings.AttemptedToFixTheGameRestart = false;
        }

19 Source : Sector.cs
with GNU General Public License v3.0
from Athlon007

public void Initialize(Vector3 size, params string[] ignoreList)
        {
            // Set the layer to Ignore Raycast layer.
            gameObject.layer = 2;

            BoxCollider collider = gameObject.AddComponent<BoxCollider>();
            collider.isTrigger = true;
            collider.size = size;

            if (ignoreList != null)
                this.ignoreList = ignoreList;

            this.transform.parent = Hypervisor.Instance.gameObject.transform;
        }

19 Source : SectorManager.cs
with GNU General Public License v3.0
from Athlon007

void CreateNewSector(Vector3 position, Vector3 size, Vector3 rotation, params string[] ignoreList)
        {
            GameObject newSector = new GameObject("MOP_Sector");
            newSector.transform.position = position;
            newSector.transform.localEulerAngles = rotation;
            Sector sectorInfo = newSector.AddComponent<Sector>();

            if (ignoreList.Length == 0)
                ignoreList = new string[0];

            sectorInfo.Initialize(size, ignoreList);
            sectors.Add(newSector);
        }

19 Source : BoxSpawner.cs
with MIT License
from BelkinAndrey

private IEnumerator Spawn()
	{
		while(true)
		{
			if (bodylist.Count > amount)
			{
				bodylist[0].Delete();
				bodylist.RemoveAt(0);
			}
			GameObject go = new GameObject("body");
			go.transform.parent = transform;
			go.transform.position = transform.position;
			LPBody body = go.AddComponent<LPBody>();
			bodylist.Add(body);
			LPFixtureCircle circle = go.AddComponent<LPFixtureCircle>();
			circle.Density = 0.2f;
			circle.Radius = 0.1f;
			body.BodyType = LPBodyTypes.Dynamic;
			body.Initialise(lpman);
			LPAPIBody.ApplyForceToCentreOfBody(body.GetPtr(),SpawnVelocity.x,SpawnVelocity.y);
			yield return new WaitForSeconds(spawninterval);
		}	
	}

19 Source : ChangeAtRuntime.cs
with MIT License
from BelkinAndrey

void FixedUpdate ()
	{
		nowtime += Time.deltaTime*mult;		
		if (nowtime >= ChangeTime)
		{
			mult = -1f;
		}
		else if(nowtime <= 0f)
		{
			mult = 1f;
		}		
		float ratio = Curve.Evaluate(nowtime / ChangeTime);
		
		Points[0] = Vector3.Lerp(new Vector3(0f,2f),new Vector3(0f,5f),ratio);
		
		//Step 1: Remove old fixture
		fix.Delete();
		
		//Step 2: Add new fixture component
		fix = gameObject.AddComponent<LPFixturePoly>();
		
		//Call DefinePoints to set the polys points programmatically
		fix.DefinePoints(Points);
		
		//Step 3: Initialise the new fixture (preplaceding in the LPBody)		
		fix.Initialise(bod);
	}

19 Source : AttachMouseQueryToMouse.cs
with MIT License
from BelkinAndrey

void Update () 
    {
        if (mouseQuery.ClickedBody != null)
        {
            // Attach with mouse joint
            if(mouseJoint == null)
            {
                mouseJoint = gameObject.AddComponent<LPJointMouse>();
                mouseJoint.BodyA = mouseQuery.ClickedBody.gameObject;
                mouseJoint.BodyB = mouseQuery.ClickedBody.gameObject;
                mouseJoint.MaximumForce = 500;
                mouseJoint.Initialise(lpMan);
            }

            bool aTouch = false;
            Vector3 touchPos = new Vector3();
            InputUtilities.GetMouseInput(out aTouch, out touchPos);
            if (aTouch)
            {
                Vector3 mousePos = Camera.main.ScreenToWorldPoint(touchPos);
                mouseJoint.SetTarget(mousePos);
            }
        }
        else
        {
           TryDeleteMouseJoint();
        }
	}

19 Source : ChangeAtRuntime.cs
with MIT License
from BelkinAndrey

void Start ()
	{
		fix = gameObject.AddComponent<LPFixturePoly>();
		fix.DefinePoints(Points);
		bod = GetComponent<LPBody>();
		bod.Initialise(FindObjectOfType<LPManager>());
	}

19 Source : SetPoly.cs
with MIT License
from BelkinAndrey

void MakePolyFix()
	{
		//Add an LPFixturePoly to the gameobject (LPBody is required so is added automatically)
		LPFixturePoly fix = PolyFix.AddComponent<LPFixturePoly>();
		
		//Call DefinePoints to set the polys points programmatically
		fix.DefinePoints(Points);
		
		//Set up the body how we want
		LPBody bod = PolyFix.GetComponent<LPBody>();
		bod.BodyType = LPBodyTypes.Dynamic;
		
		//Call initialise on the LPBody component preplaceding in the LPManager component		
		bod.Initialise(FindObjectOfType<LPManager>());
	}

19 Source : SetPoly.cs
with MIT License
from BelkinAndrey

void MakePolyPart()
	{
		//Add an LPParticleGroupPoly to the gameobject 
		LPParticleGroupPoly group = PolyPart.AddComponent<LPParticleGroupPoly>();
		
		//Call DefinePoints to set the polys points programmatically
		group.DefinePoints(Points);
		
		//Call initialise on the LPParticleGroupPoly component preplaceding in the chosen LPParticleSystem component	
		//In this case it must be particlesystem 0, as there is only one particlesystem in this scene	
		group.Initialise(FindObjectOfType<LPManager>().ParticleSystems[0]);
	}

19 Source : SetPoly.cs
with MIT License
from BelkinAndrey

void MakeChainFix()
	{
		//Add an LPFixtureChainShape to the gameobject (LPBody is required so is added automatically)
		LPFixtureChainShape fix = ChainFix.AddComponent<LPFixtureChainShape>();
		
		//Call DefinePoints to set the polys points programmatically
		fix.DefinePoints(Points);
		
		//Set up the body how we want
		LPBody bod = ChainFix.GetComponent<LPBody>();
		bod.BodyType = LPBodyTypes.Dynamic;
		
		//Call initialise on the LPBody component preplaceding in the LPManager component		
		bod.Initialise(FindObjectOfType<LPManager>());
	}

19 Source : Il2CppUtils.cs
with GNU Lesser General Public License v2.1
from BepInEx

public static Il2CppObjectBase AddComponent(Type t)
        {
            if (managerGo == null)
                managerGo = new GameObject { hideFlags = HideFlags.HideAndDontSave };

            if (!ClreplacedInjector.IsTypeRegisteredInIl2Cpp(t))
                ClreplacedInjector.RegisterTypeInIl2Cpp(t);

            return managerGo.AddComponent(Il2CppType.From(t));
        }

19 Source : ThreadingHelper.cs
with GNU Lesser General Public License v2.1
from BepInEx

internal static void Initialize()
        {
            var go = new GameObject("BepInEx_ThreadingHelper") { hideFlags = HideFlags.HideAndDontSave };
            DontDestroyOnLoad(go);
            Instance = go.AddComponent<ThreadingHelper>();
        }

19 Source : Injector.cs
with GNU General Public License v3.0
from BepInEx

public static void Inject()
		{
			if (injected)
				return;

			injected = true;
			var bootstrapper = new GameObject("Bootstrapper").AddComponent<Bootstrapper>();
			bootstrapper.Destroyed += Bootstrapper_Destroyed;
		}

19 Source : PluginComponent.cs
with GNU General Public License v3.0
from BepInEx

public static PluginComponent Create()
		{
			return new GameObject("IPA_PluginManager").AddComponent<PluginComponent>();
		}

19 Source : DependencyInjectorTests.cs
with Apache License 2.0
from bnoazx005

[UnityTest]
    public IEnumerator TestInit_CreateViewWithPlaneHierarchy_InvokesInit()
    {
        TestController.Create();

        yield return new WaitForEndOfFrame();

        bool isInitialized = false;

        GameObject viewGO = new GameObject("TestStaticView");

        viewGO.AddComponent<TestStaticView>().OnRegister = () =>
        {
            isInitialized = true;
        };

        var dependencyInjector = viewGO.AddComponent<DependencyInjector>();
        dependencyInjector.Init();

        yield return null;

        replacedert.IsTrue(isInitialized);
    }

19 Source : DependencyInjectorTests.cs
with Apache License 2.0
from bnoazx005

[UnityTest]
    public IEnumerator TestInit_CreateViewWithNestedSubviews_CorrectlyInitializesAllViews()
    {
        TestController.Create();

        yield return new WaitForEndOfFrame();

        uint actualCounter   = 0;
        uint expectedCounter = 3;

        Func<Transform, GameObject> addView = (parent) =>
        {
            GameObject go = new GameObject();

            go.AddComponent<TestStaticView>().OnRegister = () =>
            {
                actualCounter++;
            };

            go.transform.SetParent(parent);

            return go;
        };

        /*
         * The code below creates the following tree of GameObjects
         * 
         * View
         * |- SubView
         *    |-NestedView
         * -------
         */

        GameObject go1 = addView(null);
        GameObject go2 = addView(go1.transform);
        GameObject go3 = addView(go2.transform);

        var dependencyInjector = go1.AddComponent<DependencyInjector>();
        dependencyInjector.Init();

        yield return new WaitForEndOfFrame();

        replacedert.AreEqual(expectedCounter, actualCounter);
    }

19 Source : TestStaticView.cs
with Apache License 2.0
from bnoazx005

public static BaseView Create(UnityAction action = null)
    {
        GameObject go = new GameObject("TestStaticView");
        go.AddComponent<DependencyInjector>();

        TestStaticView view = go.AddComponent<TestStaticView>();
        view.OnRegister = action;

        return view;
    }

19 Source : SystemManagerObserver.cs
with Apache License 2.0
from bnoazx005

public static SystemManagerObserver CreateSystemManagerObserver(this ISystemManager systemManager, string name = null)
        {
            GameObject systemManagerObserverGO = new GameObject(name);

            SystemManagerObserver systemManagerObserver = systemManagerObserverGO.AddComponent<SystemManagerObserver>();

            systemManagerObserver.SystemManager = systemManager;

            return systemManagerObserver;
        }

19 Source : WorldContextsManager.cs
with Apache License 2.0
from bnoazx005

public void OnEvent(TNewEnreplacedyCreatedEvent eventData)
        {
            IEnreplacedy enreplacedy = mWorldContext.GetEnreplacedyById(eventData.mEnreplacedyId);

#if false//DEBUG
            Debug.Log($"[WorldContextsManager] A new enreplacedy ({enreplacedy.Name}) was created");
#endif

            GameObject enreplacedyGO = _createEnreplacedyGOView(enreplacedy, _cachedTransform);

            // initializes the observer of the enreplacedy
            EnreplacedyObserver enreplacedyObserver = enreplacedyGO.AddComponent<EnreplacedyObserver>();

            enreplacedyObserver.Init(mWorldContext, enreplacedy.Id);
        }

See More Examples