public static DontDestroyOnLoad ( System target ) : void | ||
target | System | |
return | void |
private void CreateUI() { if (canvas == null) { log.LogMessage(" "); log.LogMessage("Creating UI Elements"); // Create a GameObject with a Canvas canvas = instance.createUICanvas(); Object.DontDestroyOnLoad(canvas); // Add a Panel to the Canvas. See createUIPanel for why we pass height/width as string uiPanel = instance.createUIPanel(canvas, "550", "200", null); // This is how we'll hook mouse Events for window dragging EventTrigger comp1 = new EventTrigger(uiPanel.AddComponent(UnhollowerRuntimeLib.Il2CppType.Of <EventTrigger>()).Pointer); WindowDragHandler comp2 = new WindowDragHandler(uiPanel.AddComponent(UnhollowerRuntimeLib.Il2CppType.Of <WindowDragHandler>()).Pointer); Image panelImage = uiPanel.GetComponent <Image>(); panelImage.color = instance.HTMLString2Color("#2D2D30FF").Unbox <Color32>(); #region [Panel Elements] // NOTE: Elements are spaced in increments/decrements of 35 in localPosition #region [Add a Button] Sprite btnSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); GameObject uiButton = instance.createUIButton(uiPanel, btnSprite); uiButton.GetComponent <RectTransform>().localPosition = new Vector3(0, 250, 0); #endregion #region [Add a Toggle] Sprite toggleBgSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#3E3E42FF")); Sprite toggleSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); GameObject uiToggle = instance.createUIToggle(uiPanel, toggleBgSprite, toggleSprite); uiToggle.GetComponentInChildren <Text>().color = Color.white; uiToggle.GetComponentInChildren <Toggle>().isOn = false; uiToggle.GetComponent <RectTransform>().localPosition = new Vector3(0, 215, 0); #endregion #region [Add a Slider] Sprite sliderBgSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#9E9E9EFF")); Sprite sliderFillSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); Sprite sliderKnobSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#191919FF")); GameObject uiSlider = instance.createUISlider(uiPanel, sliderBgSprite, sliderFillSprite, sliderKnobSprite); uiSlider.GetComponentInChildren <Slider>().value = 0.5f; uiSlider.GetComponent <RectTransform>().localPosition = new Vector3(0, 185, 0); #endregion #region [Add a Text (Label)] Sprite txtBgSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); GameObject uiText = instance.createUIText(uiPanel, txtBgSprite, "#FFFFFFFF"); uiText.GetComponent <Text>().text = "This is a new Text Label"; uiText.GetComponent <RectTransform>().localPosition = new Vector3(0, 150, 0); #endregion #region [Add a InputField] Sprite inputFieldSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); GameObject uiInputField = instance.createUIInputField(uiPanel, inputFieldSprite, "#000000FF"); #region [Dev Note] // The following line is odd. It sets the text but doesn't display it, WTF? The default child object PlaceHolder // has Text component but Unhollower thinks it's a UnityEngine.Graphic? // uiInputField.transform.GetChild(0).gameObject.GetComponent<Text>().text = "Search..."; // Checked in Unity Editor too, it's definately Text, why does unhollower think it's Graphic? // // We'll just use the InputField component directly. It works, but PlaceHolder is nice... #endregion uiInputField.GetComponent <InputField>().text = "Some Input Field..."; uiInputField.GetComponent <RectTransform>().localPosition = new Vector3(0, 115, 0); #endregion #region [Add a DropDown] // NOTE: This wierd, it does it's thing and work's but then the rest on the UI disappears... hmmm... :/ Sprite dropdownBgSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); Sprite dropdownScrollbarSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#3E3E42FF")); Sprite dropdownDropDownSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#252526FF")); Sprite dropdownCheckmarkSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#7AB900FF")); Sprite dropdownMaskSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#1E1E1EFF")); GameObject uiDropDown = instance.createUIDropDown(uiPanel, dropdownBgSprite, dropdownScrollbarSprite, dropdownDropDownSprite, dropdownCheckmarkSprite, dropdownMaskSprite); Object.DontDestroyOnLoad(uiDropDown); uiDropDown.GetComponent <RectTransform>().localPosition = new Vector3(0, 75, 0); #endregion #region [Add a ScrollView] Sprite scrollviewBgSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#9E9E9EFF")); Sprite scrollviewScrollbarSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#3E3E42FF")); Sprite scrollviewMaskSprite = instance.createSpriteFrmTexture(instance.createDefaultTexture("#3E3E42FF")); GameObject uiScrollView = instance.createUIScrollView(uiPanel, scrollviewBgSprite, scrollviewMaskSprite, scrollviewScrollbarSprite); // Set some content GameObject content = uiScrollView.GetComponent <ScrollRect>().content.gameObject; GameObject contentTextObj = instance.createUIText(content, scrollviewBgSprite, "#FFFFFFFF"); contentTextObj.GetComponent <Text>().text = "ScrollView Element"; contentTextObj.GetComponent <RectTransform>().localPosition = new Vector3(120, -50, 0); uiScrollView.GetComponent <RectTransform>().localPosition = new Vector3(0, -75, 0); #endregion #region [Add a RawImage] // Our Test Sprite from testBundle for UI RawImage Element if (testAssetBundle != null && stompy != null) { log.LogMessage(" Trying to Load Test Sprite..."); stompy = testAssetBundle.LoadAsset <Sprite>("assets/tools/customassets/test assets/externaltexture.png"); if (stompy != null) { log.LogMessage(" Sprite Loaded!"); } else { log.LogMessage(" Failed to Load Sprite!"); } GameObject uiImage = instance.createUIRawImage(uiPanel, stompy); uiImage.GetComponent <RectTransform>().localPosition = new Vector3(0, -220, 0); uiImage.GetComponent <RectTransform>().localScale = new Vector3(0.3f, 0.3f); } else { log.LogMessage(" Skipping - Test AssetBundle Not Loaded!"); } #endregion #endregion isVisible = true; log.LogMessage("Complete!"); } }
/// <summary> /// Instantiates the mod and it's components. /// Looks for and loads assemblies. /// </summary> public override void OnLoad() { Game.OnSimulationToggle += Block.OnSimulationToggle; Game.OnSimulationToggle += Script.OnSimulationToggle; Game.OnBlockPlaced += block => Block.FlagForIDRebuild(); Game.OnBlockRemoved += Block.FlagForIDRebuild; Block.OnInitialisation += Script.Start; XmlSaver.OnSave += MachineData.Save; XmlLoader.OnLoad += MachineData.Load; Commands.RegisterCommand("lsm", ConfigurationCommand, "Scripter Mod configuration command."); Commands.RegisterCommand("py", PythonCommand, "Executes Python expression."); Commands.RegisterCommand("python", PythonCommand, "Executes Python expression."); Controller = new GameObject("LenchScripterMod") { hideFlags = HideFlags.DontSave }; Controller.AddComponent <ModController>(); IdentifierDisplayWindow = new IdentifierDisplayWindow(); ScriptOptionsWindow = new ScriptOptionsWindow(); WatchlistWindow = new WatchlistWindow(); Toolbar = new Toolbar { Texture = Images.IconPython, Visible = Script.Enabled, Buttons = { new Toolbar.Button { Style = new GUIStyle { normal = { background = Images.ButtonKeyNormal }, focused = { background = Images.ButtonKeyFocus }, hover = { background = Images.ButtonKeyHover }, active = { background = Images.ButtonKeyActive }, fixedWidth = 32, fixedHeight = 32 }, Text = "", OnClick = OpenIdentifier }, new Toolbar.Button { Style = new GUIStyle { normal = { background = Images.ButtonListNormal }, focused = { background = Images.ButtonListFocus }, hover = { background = Images.ButtonListHover }, active = { background = Images.ButtonListActive }, fixedWidth = 32, fixedHeight = 32 }, Text = "", OnClick = OpenWatchlist }, new Toolbar.Button { Style = new GUIStyle { normal = { background = Images.ButtonScriptNormal }, focused = { background = Images.ButtonScriptFocus }, hover = { background = Images.ButtonScriptHover }, active = { background = Images.ButtonScriptActive }, fixedWidth = 32, fixedHeight = 32 }, Text = "", OnClick = OpenScript }, new Toolbar.Button { Style = new GUIStyle() { normal = { background = Images.ButtonSettingsNormal }, focused = { background = Images.ButtonSettingsFocus }, hover = { background = Images.ButtonSettingsHover }, active = { background = Images.ButtonSettingsActive }, fixedWidth = 32, fixedHeight = 32 }, Text = "", OnClick = OpenSettings } } }; Object.DontDestroyOnLoad(DependencyInstaller.Instance); LoadedAPI = true; Configuration.Load(); EnableScriptButton = new SettingsButton { Text = "SCRIPT", Value = Script.Enabled, OnToggle = enabled => { Script.Enabled = enabled; Toolbar.Visible = enabled; } }; EnableScriptButton.Create(); PythonVersion2Button = new OptionsButton { Text = "Python 2.7", Value = PythonEnvironment.Version == "ironpython2.7", OnToggle = enabled => { if (enabled) { if (PythonEnvironment.Version != "ironpython3.0") { return; } PythonVersion3Button.Value = false; Script.SetVersionAndReload("ironpython2.7"); } else { PythonVersion2Button.Value = true; } } }; PythonVersion2Button.Create(); PythonVersion3Button = new OptionsButton { Text = "Python 3.0", Value = PythonEnvironment.Version == "ironpython3.0", OnToggle = enabled => { if (enabled) { if (PythonEnvironment.Version != "ironpython2.7") { return; } PythonVersion2Button.Value = false; Script.SetVersionAndReload("ironpython3.0"); } else { PythonVersion3Button.Value = true; } } }; PythonVersion3Button.Create(); if (UpdateCheckerEnabled) { CheckForModUpdate(); } }
public static void Init() { _load = new GameObject(); _load.AddComponent <Main>(); Object.DontDestroyOnLoad(_load); }
private static void SpawnCrestActionPoint() { LewdCrestXPlugin.Logger.LogDebug("Spawning crest action point"); if (_iconOff == null) { _iconOff = (LewdCrestXPlugin.Bundle.LoadAsset <Texture2D>("action_icon_crest_off") ?? throw new Exception("asset not found - action_icon_crest_off")).ToSprite(); Object.DontDestroyOnLoad(_iconOff); } if (_iconOn == null) { _iconOn = (LewdCrestXPlugin.Bundle.LoadAsset <Texture2D>("action_icon_crest_on") ?? throw new Exception("asset not found - action_icon_crest_on")).ToSprite(); Object.DontDestroyOnLoad(_iconOn); } var inst = CommonLib.LoadAsset <GameObject>("map/playeractionpoint/00.unity3d", "PlayerActionPoint_05", true); var parent = GameObject.Find("Map/ActionPoints"); inst.transform.SetParent(parent.transform, true); var pap = inst.GetComponentInChildren <PlayerActionPoint>(); var iconRootObject = pap.gameObject; var iconRootTransform = pap.transform; Object.DestroyImmediate(pap, false); // position above the small table iconRootTransform.position = new Vector3(-3.1f, -0.4f, 1.85f); var evt = iconRootObject.AddComponent <TriggerEnterExitEvent>(); var animator = iconRootObject.GetComponentInChildren <Animator>(); var rendererIcon = iconRootObject.GetComponentInChildren <SpriteRenderer>(); rendererIcon.sprite = _iconOff; var playerInRange = false; evt.onTriggerEnter += c => { if (!c.CompareTag("Player")) { return; } playerInRange = true; animator.Play("icon_action"); rendererIcon.sprite = _iconOn; c.GetComponent <Player>().actionPointList.Add(evt); }; evt.onTriggerExit += c => { if (!c.CompareTag("Player")) { return; } playerInRange = false; animator.Play("icon_stop"); rendererIcon.sprite = _iconOff; c.GetComponent <Player>().actionPointList.Remove(evt); }; var player = Singleton <Game> .Instance.actScene.Player; evt.UpdateAsObservable() .Subscribe(_ => { // Hide in H scenes and other places var isVisible = Singleton <Game> .IsInstance() && !Singleton <Game> .Instance.IsRegulate(true); if (rendererIcon.enabled != isVisible) { rendererIcon.enabled = isVisible; } // Check if player clicked this point if (isVisible && playerInRange && ActionInput.isAction && !player.isActionNow) { ClubInterface.ShowWindow = true; } }) .AddTo(evt); evt.OnGUIAsObservable() .Subscribe(ClubInterface.OnGui) .AddTo(evt); }
public SRDebugService() { SRServiceManager.RegisterService <IDebugService>(this); // Load profiler SRServiceManager.GetService <IProfilerService>(); // Setup trigger service _debugTrigger = SRServiceManager.GetService <IDebugTriggerService>(); _informationService = SRServiceManager.GetService <ISystemInformationService>(); _pinnedUiService = SRServiceManager.GetService <IPinnedUIService>(); _pinnedUiService.OptionsCanvasCreated += transform => { if (PinnedUiCanvasCreated == null) { return; } try { PinnedUiCanvasCreated(transform); } catch (Exception e) { Debug.LogException(e); } }; _optionsService = SRServiceManager.GetService <IOptionsService>(); // Create debug panel service (this does not actually load any UI resources until opened) _debugPanelService = SRServiceManager.GetService <IDebugPanelService>(); // Subscribe to visibility changes to provide API-facing event for panel open/close _debugPanelService.VisibilityChanged += DebugPanelServiceOnVisibilityChanged; _debugTrigger.IsEnabled = Settings.EnableTrigger == Settings.TriggerEnableModes.Enabled || Settings.EnableTrigger == Settings.TriggerEnableModes.MobileOnly && Application.isMobilePlatform || Settings.EnableTrigger == Settings.TriggerEnableModes.DevelopmentBuildsOnly && Debug.isDebugBuild; _debugTrigger.Position = Settings.TriggerPosition; if (Settings.EnableKeyboardShortcuts) { SRServiceManager.GetService <KeyboardShortcutListenerService>(); } #if RELEASE _entryCodeEnabled = Settings.Instance.RequireCode && Settings.Instance.EntryCode.Count == 4; if (Settings.Instance.RequireCode && !_entryCodeEnabled) { Debug.LogError("[SRDebugger] RequireCode is enabled, but pin is not 4 digits"); } #else _entryCodeEnabled = false; #endif // Ensure that root object cannot be destroyed on scene loads var srDebuggerParent = Hierarchy.Get("SRDebugger"); Object.DontDestroyOnLoad(srDebuggerParent.gameObject); }
private void SceneManagerOnSceneLoaded(Scene scene, LoadSceneMode mode) { if (scene.name == MenuSceneName) { if (_resetNoFail) { var resultsViewController = Resources.FindObjectsOfTypeAll <ResultsViewController>().FirstOrDefault(); if (resultsViewController != null) { resultsViewController.continueButtonPressedEvent += ResultsViewControllerOnContinueButtonPressedEvent; } } if (SettingsObject != null) { return; } var volumeSettings = Resources.FindObjectsOfTypeAll <VolumeSettingsController>().FirstOrDefault(); if (volumeSettings == null) { return; } volumeSettings.gameObject.SetActive(false); SettingsObject = Object.Instantiate(volumeSettings.gameObject); SettingsObject.SetActive(false); volumeSettings.gameObject.SetActive(true); if (SettingsObject == null) { return; } var volume = SettingsObject.GetComponent <VolumeSettingsController>(); ReflectionUtil.CopyComponent(volume, typeof(IncDecSettingsController), typeof(SpeedSettingsController), SettingsObject); Object.DestroyImmediate(volume); SettingsObject.GetComponentInChildren <TMP_Text>().text = "SPEED"; Object.DontDestroyOnLoad(SettingsObject); } else if (scene.name == GameSceneName) { CustomEffectPoolsInstaller customEffectPoolsInstaller = null; var effectPoolsInstaller = Resources.FindObjectsOfTypeAll <EffectPoolsInstaller>().FirstOrDefault(); if (effectPoolsInstaller != null) { customEffectPoolsInstaller = (CustomEffectPoolsInstaller)ReflectionUtil.CopyComponent(effectPoolsInstaller, typeof(EffectPoolsInstaller), typeof(CustomEffectPoolsInstaller), effectPoolsInstaller.gameObject); } SceneContext sceneContext = null; SceneDecoratorContext sceneDecoratorContext = null; foreach (var gameObject in scene.GetRootGameObjects()) { if (sceneContext == null) { sceneContext = gameObject.GetComponentInChildren <SceneContext>(true); } } foreach (var gameObject in SceneManager.GetSceneByName(ContextSceneName).GetRootGameObjects()) { if (sceneDecoratorContext == null) { sceneDecoratorContext = gameObject.GetComponentInChildren <SceneDecoratorContext>(true); } } if (sceneContext != null && sceneDecoratorContext != null) { var prop = typeof(Context).GetField("_installers", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); var installersList = (List <MonoInstaller>)prop.GetValue(sceneDecoratorContext); installersList.Remove(effectPoolsInstaller); Object.DestroyImmediate(effectPoolsInstaller); installersList.Add(customEffectPoolsInstaller); } if (_mainGameSceneSetupData == null) { _mainGameSceneSetupData = Resources.FindObjectsOfTypeAll <MainGameSceneSetupData>().FirstOrDefault(); if (_mainGameSceneSetupData == null) { return; } _mainGameSceneSetupData.didFinishEvent += MainGameSceneSetupDataOnDidFinishEvent; } if (_lastLevelId != _mainGameSceneSetupData.difficultyLevel.level.levelID && !string.IsNullOrEmpty(_lastLevelId)) { PlayingNewSong = true; HasTimeScaleChanged = false; TimeScale = 1; _lastLevelId = _mainGameSceneSetupData.difficultyLevel.level.levelID; } else { PlayingNewSong = false; } if (IsEqualToOne(TimeScale)) { HasTimeScaleChanged = false; } _lastLevelId = _mainGameSceneSetupData.difficultyLevel.level.levelID; AudioTimeSync = Resources.FindObjectsOfTypeAll <AudioTimeSyncController>().FirstOrDefault(); _songAudio = AudioTimeSync.GetPrivateField <AudioSource>("_audioSource"); NoFail = !_mainGameSceneSetupData.gameplayOptions.validForScoreUse; if (!NoFail) { TimeScale = Mathf.Clamp(TimeScale, 1, MaxSize); } var canvas = Resources.FindObjectsOfTypeAll <HorizontalLayoutGroup>() .FirstOrDefault(x => x.name == "Buttons") ?.transform.parent; if (canvas == null) { return; } _uiElementsCreator = canvas.gameObject.AddComponent <UIElementsCreator>(); _uiElementsCreator.ValueChangedEvent += UIElementsCreatorOnValueChangedEvent; _uiElementsCreator.Init(); TimeScale = TimeScale; } }
/// <summary> /// DontDestroyOnLoadにする /// </summary> public static GameObject DontDestroyOnLoad(this GameObject self) { Object.DontDestroyOnLoad(self); return(self); }
public void SpawnPlayer( ushort id, string name, Math.Vector2 position, bool scale, Team team, byte skinId ) { if (_playerData.ContainsKey(id)) { Logger.Get().Warn(this, $"We already have created a player object for ID {id}"); return; } // Create a player container var playerContainer = new GameObject($"Player Container {id}"); playerContainer.transform.position = new Vector3(position.X, position.Y); playerContainer.AddComponent <PositionInterpolation>(); // Instantiate the player object from the prefab in the player container var playerObject = Object.Instantiate( _playerPrefab, playerContainer.transform ); Object.DontDestroyOnLoad(playerObject); SetPlayerObjectBoolScale(playerObject, scale); // Set object and children to active playerObject.SetActive(true); playerObject.SetActiveChildren(true); // Now we need to copy over a lot of variables from the local player object var localPlayerObject = HeroController.instance.gameObject; // Obtain colliders from both objects var collider = playerObject.GetComponent <BoxCollider2D>(); var localCollider = localPlayerObject.GetComponent <BoxCollider2D>(); // Copy collider offset and size collider.isTrigger = true; collider.offset = localCollider.offset; collider.size = localCollider.size; collider.enabled = true; // Copy collider bounds var bounds = collider.bounds; var localBounds = localCollider.bounds; bounds.min = localBounds.min; bounds.max = localBounds.max; // Disable DamageHero component unless pvp is enabled if (_gameSettings.IsPvpEnabled && _gameSettings.IsBodyDamageEnabled) { playerObject.layer = 11; playerObject.GetComponent <DamageHero>().enabled = true; } else { playerObject.layer = 9; playerObject.GetComponent <DamageHero>().enabled = false; } // Copy over mesh filter variables var meshFilter = playerObject.GetComponent <MeshFilter>(); var mesh = meshFilter.mesh; var localMesh = localPlayerObject.GetComponent <MeshFilter>().sharedMesh; mesh.vertices = localMesh.vertices; mesh.normals = localMesh.normals; mesh.uv = localMesh.uv; mesh.triangles = localMesh.triangles; mesh.tangents = localMesh.tangents; // Copy mesh renderer material var meshRenderer = playerObject.GetComponent <MeshRenderer>(); meshRenderer.material = new Material(localPlayerObject.GetComponent <MeshRenderer>().material); // Disable non bouncer component var nonBouncer = playerObject.GetComponent <NonBouncer>(); nonBouncer.active = false; // Copy over animation library var spriteAnimator = playerObject.GetComponent <tk2dSpriteAnimator>(); // Make a smart copy of the sprite animator library so we can // modify the animator without having to worry about other player objects spriteAnimator.Library = CopyUtil.SmartCopySpriteAnimation( localPlayerObject.GetComponent <tk2dSpriteAnimator>().Library, playerObject ); AddNameToPlayer(playerContainer, name, team); // Let the SkinManager update the skin _skinManager.UpdatePlayerSkin(playerObject, skinId); // Store the player data in the mapping _playerData[id] = new ClientPlayerData( playerContainer, playerObject, team ); // Set whether this player should have body damage // Only if: // PvP is enabled and body damage is enabled AND // (the teams are not equal or if either doesn't have a team) ToggleBodyDamage( _playerData[id], _gameSettings.IsPvpEnabled && _gameSettings.IsBodyDamageEnabled && (team != LocalPlayerTeam || team.Equals(Team.None) || LocalPlayerTeam.Equals(Team.None)) ); }
private void InitializeGlobalData() { if (_globalData == null) { _globalData = new GlobalData(); } _globalData.Origin = GameObject.Find("slide")?.transform.position ?? Vector3.zero; _globalData.TreeOrigin = GameObject.Find("stool")?.transform.position ?? Vector3.zero; // Tree Teleport Stuff if (_globalData.BigTreeTeleportToMap == null) { var teleporterPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(MapFileUtils).Assembly.Location), Constants.MiscObjectsFolderName, "Teleporter"); AssetBundle bundle = MapFileUtils.GetAssetBundleFromZip(teleporterPath); _globalData.BigTreeTeleportToMap = Object.Instantiate(bundle.LoadAsset <GameObject>("_Teleporter")); _globalData.BigTreeTeleportToMap.layer = Constants.MaskLayerPlayerTrigger; Object.DontDestroyOnLoad(_globalData.BigTreeTeleportToMap); _globalData.BigTreeTeleportToMap.transform.position += new Vector3(0, -0.05f, 2.9f); _globalData.BigTreeTeleportToMap.transform.Rotate(new Vector3(0, 20, 0)); } var orbPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(MapFileUtils).Assembly.Location), Constants.MiscObjectsFolderName, "Orb"); AssetBundle orbBundle = MapFileUtils.GetAssetBundleFromZip(orbPath); GameObject orb = Object.Instantiate(orbBundle.LoadAsset <GameObject>("_Orb")); GameObject orbVisuals = Object.Instantiate(orb); orb.AddComponent <RotateByHand>(); orb.GetComponent <Renderer>().enabled = false; Object.Destroy(orb.GetComponent <Renderer>()); orb.layer = 18; orbVisuals.transform.SetParent(orb.transform); orbVisuals.transform.localPosition = Vector3.zero; orbVisuals.transform.localScale = Vector3.one; orbVisuals.transform.localRotation = Quaternion.identity; orbVisuals.AddComponent <PreviewOrb>(); orbVisuals.GetComponent <Collider>().enabled = false; Object.Destroy(orbVisuals.GetComponent <Collider>()); //orb.layer = Constants.MaskLayerPlayerTrigger; Teleporter treeTeleporter = _globalData.BigTreeTeleportToMap.GetComponent <Teleporter>(); treeTeleporter.TeleporterType = TeleporterType.Map; treeTeleporter.JoinGameOnTeleport = true; treeTeleporter.TeleportPoints = new List <Transform>(); treeTeleporter.Delay = 1.5f; treeTeleporter.TouchType = GorillaTouchType.Head; Object.DontDestroyOnLoad(treeTeleporter); if (_globalData.BigTreePoint == null) { _globalData.BigTreePoint = new GameObject("TreeHomeTargetObject"); _globalData.BigTreePoint.transform.position = new Vector3(-66f, 12.3f, -83f); _globalData.BigTreePoint.transform.rotation = Quaternion.Euler(0f, -90f, 0f); Object.DontDestroyOnLoad(_globalData.BigTreePoint); } treeTeleporter.TeleportPoints.Add(_globalData.BigTreePoint.transform); ColorTreeTeleporter(new Color(0, 1, 0)); // Emergency Teleport Stuff if (_globalData.FallEmergencyTeleport != null) { Object.Destroy(_globalData.FallEmergencyTeleport); _globalData.FallEmergencyTeleport = null; } _globalData.FallEmergencyTeleport = new GameObject("FallEmergencyTeleport"); _globalData.FallEmergencyTeleport.layer = Constants.MaskLayerHandTrigger; _globalData.FallEmergencyTeleport.AddComponent <BoxCollider>().isTrigger = true; _globalData.FallEmergencyTeleport.transform.localScale = new Vector3(1000f, 1f, 1000f); _globalData.FallEmergencyTeleport.transform.position = _globalData.TreeOrigin + new Vector3(0f, -200f, 0f); Object.DontDestroyOnLoad(_globalData.FallEmergencyTeleport); Teleporter emergencyFallTeleporter = _globalData.FallEmergencyTeleport.AddComponent <Teleporter>(); emergencyFallTeleporter.TeleportPoints = new List <Transform>() { _globalData.BigTreePoint.transform }; }
public override void Init() { Canvas = GameObject.Find("UIRoot").GetComponent <Canvas>(); Object.DontDestroyOnLoad(Canvas); _res = Res.Create(); }
public static void BuildMenu(GameObject canvas) { Texture2D buttonImg = GUIController.Instance.images["Button_BG"]; Texture2D inputImg = GUIController.Instance.images["Input_BG"]; Texture2D panelImg = GUIController.Instance.images["Panel_BG"]; Texture2D teamImg = GUIController.Instance.images["Team_BG"]; Texture2D chatImg = GUIController.Instance.images["Chat_BG"]; Texture2D sendImg = GUIController.Instance.images["Send_BG"]; float x = Screen.width / 2.0f - inputImg.width / 2.0f - 30.0f; float y = 30.0f; EventSystem eventSystem = null; if (!GameObject.Find("EventSystem")) { GameObject eventSystemObj = new GameObject("EventSystem"); eventSystem = eventSystemObj.AddComponent <EventSystem>(); eventSystem.sendNavigationEvents = true; eventSystem.pixelDragThreshold = 10; eventSystemObj.AddComponent <StandaloneInputModule>(); Object.DontDestroyOnLoad(eventSystemObj); } Panel = new CanvasPanel( canvas, panelImg, new Vector2(x, y), Vector2.zero, new Rect(0, 0, panelImg.width, panelImg.height) ); Panel.AddText( "Connection Text", "Connection", new Vector2(x, y), new Vector2(buttonImg.width, buttonImg.height), GUIController.Instance.trajanNormal, 24, FontStyle.Bold, TextAnchor.MiddleCenter ); y += buttonImg.height + 10; _ipInput = Panel.AddInput( "IP Input", inputImg, new Vector2(x, y), Vector2.zero, new Rect(0, y, inputImg.width, inputImg.height), GUIController.Instance.trajanNormal, MultiplayerClient.settings.host, "Address", 16 ); y += inputImg.height + 5; _portInput = Panel.AddInput( "Port Input", inputImg, new Vector2(x, y), Vector2.zero, new Rect(0, y, inputImg.width, inputImg.height), GUIController.Instance.trajanNormal, MultiplayerClient.settings.port.ToString(), "Port", 16 ); y += inputImg.height + 5; _usernameInput = Panel.AddInput( "Username Input", inputImg, new Vector2(x, y), Vector2.zero, new Rect(0, y, inputImg.width, inputImg.height), GUIController.Instance.trajanNormal, MultiplayerClient.settings.username, "Username", 16 ); y += inputImg.height + 5; /*Panel.AddText( * "Team Text", * "Teams", * new Vector2(x, y), * new Vector2(buttonImg.width, buttonImg.height), * GUIController.Instance.trajanNormal, * 24, * FontStyle.Bold, * TextAnchor.MiddleCenter * ); * y += buttonImg.height + 10;*/ TeamButton = Panel.AddButton( "Team Button", teamImg, new Vector2(x, y), Vector2.zero, ToggleTeam, new Rect(0, y, teamImg.width, teamImg.height), GUIController.Instance.trajanNormal, "None", 16 ); y += teamImg.height + 5; ConnectButton = Panel.AddButton( "Connect Button", buttonImg, new Vector2(x, y), Vector2.zero, ToggleConnectToServer, new Rect(0, y, buttonImg.width, buttonImg.height), GUIController.Instance.trajanNormal, "Connect", 16 ); y += buttonImg.height; _chatInput = Panel.AddInput( "Chat Input", chatImg, new Vector2(x - 25, y), Vector2.zero, new Rect(0, y, chatImg.width, chatImg.height), GUIController.Instance.trajanNormal, "", "Chat", 16 ); SendButton = Panel.AddButton( "Send Button", sendImg, new Vector2(x + chatImg.width - 23, y), Vector2.zero, SendMessage, new Rect(0, y, sendImg.width, sendImg.height), GUIController.Instance.trajanNormal, "", 16 ); y += chatImg.height + 5; ConnectionInfo = new CanvasText( canvas, new Vector2(Screen.width / 2 - 500, Screen.height - 70), new Vector2(1000.0f, 50.0f), GUIController.Instance.trajanBold, "Disconnected.", fontSize: 42, alignment: TextAnchor.UpperCenter ); if (eventSystem != null) { eventSystem.firstSelectedGameObject = _ipInput.InputObject; } ConnectionInfo.SetActive(false); Panel.SetActive(false, true); On.HeroController.Pause += OnPause; On.HeroController.UnPause += OnUnPause; UnityEngine.SceneManagement.SceneManager.activeSceneChanged += OnSceneChange; }
public IEnumerator UnitySetUp() => UniTask.ToCoroutine(async() => { Console.WriteLine($"[MirageTest] UnitySetUp class:{TestContext.CurrentContext.Test.ClassName} method:{TestContext.CurrentContext.Test.MethodName} "); serverGo = new GameObject("server", typeof(ServerObjectManager), typeof(NetworkServer)); clientGo = new GameObject("client", typeof(ClientObjectManager), typeof(NetworkClient)); socketFactory = serverGo.AddComponent <TestSocketFactory>(); server = serverGo.GetComponent <NetworkServer>(); client = clientGo.GetComponent <NetworkClient>(); if (ServerConfig != null) { server.PeerConfig = ServerConfig; } if (ClientConfig != null) { client.PeerConfig = ClientConfig; } server.SocketFactory = socketFactory; client.SocketFactory = socketFactory; serverObjectManager = serverGo.GetComponent <ServerObjectManager>(); serverObjectManager.Server = server; clientObjectManager = clientGo.GetComponent <ClientObjectManager>(); clientObjectManager.Client = client; ExtraSetup(); // wait 2 frames for start to be called await UniTask.DelayFrame(2); // create and register a prefab playerPrefab = new GameObject("player (unspawned)", typeof(NetworkIdentity), typeof(T)); // DontDestroyOnLoad so that "prefab" wont be destroyed by scene loading // also means that NetworkScenePostProcess will skip this unspawned object Object.DontDestroyOnLoad(playerPrefab); var identity = playerPrefab.GetComponent <NetworkIdentity>(); identity.PrefabHash = Guid.NewGuid().GetHashCode(); clientObjectManager.RegisterPrefab(identity); // wait for client and server to initialize themselves await UniTask.Delay(1); // start the server var started = new UniTaskCompletionSource(); server.Started.AddListener(() => started.TrySetResult()); server.StartServer(); await started.Task; if (AutoConnectClient) { // now start the client client.Connect("localhost"); await AsyncUtil.WaitUntilWithTimeout(() => server.Players.Count > 0); // get the connections so that we can spawn players serverPlayer = server.Players.First(); clientPlayer = client.Player; // create a player object in the server serverPlayerGO = Object.Instantiate(playerPrefab); serverPlayerGO.name = "player (server)"; serverIdentity = serverPlayerGO.GetComponent <NetworkIdentity>(); serverComponent = serverPlayerGO.GetComponent <T>(); serverObjectManager.AddCharacter(serverPlayer, serverPlayerGO); // wait for client to spawn it await AsyncUtil.WaitUntilWithTimeout(() => clientPlayer.HasCharacter); clientIdentity = clientPlayer.Identity; clientPlayerGO = clientIdentity.gameObject; clientPlayerGO.name = "player (client)"; clientComponent = clientPlayerGO.GetComponent <T>(); } await LateSetup(); });
/// <summary> /// Tries to find the appropriate object reference for the attached field. /// This should be called on scene load <b>before</b> anything messes with /// it to ensure the objects aren't destroyed. /// </summary> public static void FindReferences(Scene scene) { // A list of every GameObject in the scene var gameObjects = scene.GetAllGameObjectsInScene(); // First we find every field that uses this attribute foreach (var field in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).SelectMany(x => x.GetFields())) { // Find our attributes on that field and continue if there aren't any var attributes = field.GetCustomAttributes(typeof(ObjectReferenceAttribute), true).Cast <ObjectReferenceAttribute>().ToArray(); if (attributes.Length == 0) { continue; } // Reset the field and go over each found attribute //field.SetValue(null, null); foreach (var reference in attributes) { // If the field's value is already set, break. // NOTE: Objects are "deleted" on scene load, but reflection will not necessarily return null immediately. // This method is only run on scene load anyway, so the duplicate checking isn't super necessary. if (field.GetValue(null) as Object) { break; } // If the field type is GameObject, just find the GameObject normally Object found; if (field.FieldType == typeof(GameObject)) { found = gameObjects.FirstOrDefault(x => x.name.Contains(reference.NameFilter)); } // If it isn't, we also want to query for where it has a component of the right type else { found = gameObjects.Where(x => x.name.Contains(reference.NameFilter)).FirstOrDefault(x => x.GetComponent(field.FieldType))?.GetComponent(field.FieldType); } if (found == null) { continue; } field.SetValue(null, found); if (!reference.DontDestroyOnLoad) { continue; } if (found is GameObject go) { go.transform.parent = null; go.transform.position = Vector3.down * 1000; } else { ((Component)found).transform.parent = null; ((Component)found).transform.position = Vector3.down * 1000; } Object.DontDestroyOnLoad(found); } } }
private Object InstanciateMonoBehaviourObject(Type implementationType, bool isSingleton) { var instance = isSingleton ? FindObjectOfType(implementationType) : null; if (instance != null) { Debug.LogWarningFormat( "{0} Using instance already created '{1}' for {2}", RootObjName, instance, implementationType); if (!Application.isPlaying) { return(instance); } var component = instance as Component; if (component != null) { Object.DontDestroyOnLoad(component.gameObject); } Object.DontDestroyOnLoad(instance); return(instance); } GameObject rootObj; if (isSingleton) { rootObj = GameObject.Find(RootObjName); if (rootObj == null) { rootObj = new GameObject(RootObjName) { hideFlags = DefaultHideFlags }; Debug.LogFormat("Created {0}", rootObj.name); if (Application.isPlaying) { Object.DontDestroyOnLoad(rootObj); } #if UNITY_EDITOR _singletonsList = rootObj.AddComponent <SingletonsListComponent>(); #endif } } else { rootObj = new GameObject(implementationType.Name) { hideFlags = DefaultHideFlags }; Debug.LogFormat("Created {0}", rootObj.name); } instance = rootObj.AddComponent(implementationType); if (instance == null) { Debug.LogErrorFormat( "{1} Cannot instantiate: {0}", implementationType.Name, rootObj.name); return(null); } Debug.LogFormat( "{2} Instance of '{0}' added to '{1}'", implementationType.Name, rootObj, rootObj.name); return(instance); }
private static void InitRoot() { //根 UIRoot———————————————————————————————————— GameObject go = new GameObject("UIRoot"); Object.DontDestroyOnLoad(go); go.layer = LayerMask.NameToLayer("UI"); m_Instance = go.AddComponent <UIRoot>(); Transform rooTransform = go.transform; rooTransform.position = Vector3.zero; m_Instance.RootTransform = rooTransform; //Canvas——————————————————— GameObject canvas = CreateGameObject("Canvas", rooTransform, Vector3.zero); canvas.AddComponent <RectTransform>(); Canvas can = canvas.AddComponent <Canvas>(); m_Instance.RootCanvas = can; can.renderMode = RenderMode.ScreenSpaceCamera; can.planeDistance = 8; can.pixelPerfect = true; CanvasScaler cs = canvas.AddComponent <CanvasScaler>(); cs.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; cs.referenceResolution = mReferenceResolution; cs.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand; //GraphicRaycaster———————————————————————————————————— m_Instance.mGR = canvas.AddComponent <GraphicRaycaster>(); //UICamera———————————————————————————————————— GameObject camObj = CreateGameObject("UICamera", rooTransform, Vector3.zero); Camera cam = camObj.AddComponent <Camera>(); cam.clearFlags = CameraClearFlags.Depth; // 这次设置成 2D相机 cam.orthographic = true; cam.nearClipPlane = 0.1f; cam.farClipPlane = 100; // cam.fieldOfView = 45; cam.nearClipPlane = -15f; cam.farClipPlane = 15f; can.worldCamera = cam; // cam.cullingMask = 1 << 5; cam.depth = 10; cam.allowHDR = false; m_Instance.UICamera = cam; camObj.AddComponent <AudioListener>(); camObj.AddComponent <FlareLayer>(); //EventSystem———————————————————————————————————— GameObject eventObj = CreateGameObject("EventSystem", rooTransform, Vector3.zero); eventObj.AddComponent <EventSystem>(); eventObj.AddComponent <StandaloneInputModule>(); //———————————————————————————————————— string[] sceneNames = Enum.GetNames(typeof(EF_Scenes)); m_Instance.UITransforms = new Transform[sceneNames.Length]; for (int i = 0; i < sceneNames.Length; i++) { m_Instance.UITransforms[i] = CreateUI(sceneNames[i], canvas.transform); } m_Instance.FirstUiTransform = CreateUI("FirstView", canvas.transform); }
private static void CreateManagersBehavioursHolder() { behavioursHolder = new GameObject(ManagersBehavioursParentName).transform; Object.DontDestroyOnLoad(behavioursHolder.gameObject); }
public InputComponent( ComponentGroup componentGroup, Vector2 position, Vector2 size, string defaultValue, string placeholderText, MultiStateSprite bgSprite, Font font, int fontSize, InputField.CharacterValidation characterValidation = InputField.CharacterValidation.None, int characterLimit = 0 ) : base(componentGroup, position, size) { _bgSprite = bgSprite; Interactable = true; // Create background image Image = GameObject.AddComponent <Image>(); Image.sprite = bgSprite.Neutral; Image.type = Image.Type.Sliced; var placeholder = new GameObject(); placeholder.AddComponent <RectTransform>().sizeDelta = size; var placeholderTextComponent = placeholder.AddComponent <Text>(); placeholderTextComponent.text = placeholderText; placeholderTextComponent.font = font; placeholderTextComponent.fontSize = fontSize; placeholderTextComponent.alignment = TextAnchor.MiddleCenter; // Make the color white with opacity so it is clearly different from inputted text placeholderTextComponent.color = new Color(1f, 1f, 1f, 0.5f); // Set the transform parent to the InputComponent gameObject placeholder.transform.SetParent(GameObject.transform, false); Object.DontDestroyOnLoad(placeholder); var textObject = new GameObject(); textObject.AddComponent <RectTransform>().sizeDelta = size - new Vector2(TextMargin * 2f, 0f); Text = textObject.AddComponent <Text>(); Text.text = defaultValue; Text.font = font; Text.fontSize = fontSize; Text.alignment = TextAnchor.MiddleCenter; Text.color = Color.white; // Set the transform parent to the InputComponent gameObject textObject.transform.SetParent(GameObject.transform, false); Object.DontDestroyOnLoad(textObject); // Create the actual inputField component InputField = GameObject.AddComponent <InputField>(); InputField.targetGraphic = Image; InputField.placeholder = placeholderTextComponent; InputField.textComponent = Text; InputField.text = defaultValue; InputField.characterValidation = characterValidation; InputField.characterLimit = characterLimit; InputField.shouldActivateOnSelect = false; InputField.onValueChanged.AddListener(value => { _onChange?.Invoke(value); }); var eventTrigger = GameObject.AddComponent <EventTrigger>(); AddEventTrigger(eventTrigger, EventTriggerType.PointerEnter, data => { if (Interactable) { Image.sprite = bgSprite.Hover; } }); AddEventTrigger(eventTrigger, EventTriggerType.PointerExit, data => { if (Interactable) { Image.sprite = bgSprite.Neutral; } }); AddEventTrigger(eventTrigger, EventTriggerType.PointerDown, data => { if (Interactable) { Image.sprite = bgSprite.Active; } }); }
/// <summary> /// 转场不销毁 /// </summary> /// <param name="go_"></param> static public void DontDestroyOnLoad(GameObject go_) { Object.DontDestroyOnLoad(go_); }
public static void DontDestroyOnLoad(this UObject o) { UObject.DontDestroyOnLoad(o); }
public static IEnumerator CreateTemplates() { // ---------- First load the built-in silhouette and other necessary assets ---------- // var top = new GameObject("silhouette_template"); Object.DontDestroyOnLoad(top); var modelObj = CommonLib.LoadAsset <GameObject>("chara/oo_base.unity3d", "p_cm_body_00_low", true, "abdata"); var modelRend = PrepareSilhouetteRenderer(modelObj); GameObject animObj; if (modelRend != null) { animObj = CommonLib.LoadAsset <GameObject>("chara/oo_base.unity3d", "p_cf_body_bone_low", true, "abdata"); } else { // The fallback is needed for KK Party, posibly pre-darkness KK Object.Destroy(modelObj); modelObj = CommonLib.LoadAsset <GameObject>("chara/oo_base.unity3d", "p_cm_body_00", true, "abdata"); modelRend = PrepareSilhouetteRenderer(modelObj); if (modelRend == null) { Object.Destroy(modelObj); throw new InvalidOperationException("Could not find silhouette model data"); } animObj = CommonLib.LoadAsset <GameObject>("chara/oo_base.unity3d", "p_cf_body_bone", true, "abdata"); } var animCmp = animObj.GetComponent <Animator>(); foreach (var c in animObj.GetComponentsInChildren(typeof(Component), true)) { if (c is Animator || c is Transform) { continue; } // Get rid of useless performance-eating scripts // Can't DestroyImmediate these two because other components rely on them so they have to be removed later if (c is BaseData || c is NeckLookCalcVer2) { Object.Destroy(c); } else { Object.DestroyImmediate(c); } } var animObjCopy = Object.Instantiate(animObj); modelObj.transform.SetParent(top.transform); animObj.transform.SetParent(top.transform); RemoveCloneTagsFromName(modelObj); RemoveCloneTagsFromName(animObj); // Replace mesh bones with animator bones var animBones = animCmp.GetComponentsInChildren <Transform>(true); var modelBones = modelRend.bones.ToArray(); for (var i = 0; i < modelBones.Length; i++) { modelBones[i] = animBones.First(x => x.name == modelBones[i].name); } modelRend.rootBone = animBones.First(x => x.name == "cf_j_root"); modelRend.bones = modelBones; // Destroy no longer used bones Object.Destroy(modelObj.transform.Find("cf_j_root")?.gameObject); // Not used Object.Destroy(modelObj.transform.Find("cf_o_root/n_cm_body")?.gameObject); Object.Destroy(modelObj.transform.Find("cf_o_root/n_tang")?.gameObject); var animBundle = AssetBundle.LoadFromFile(@"abdata\action\animator\00.unity3d"); var animBase = animBundle.LoadAsset("base"); var ctrl = (RuntimeAnimatorController)Object.Instantiate(animBase); animCmp.runtimeAnimatorController = ctrl; animBundle.Unload(false); SetupNavmeshObstacle(top); top.SetActive(false); _swimsuitSilhouetteTemplates = new List <GameObject> { top }; //todo more kinds? with hair? // Allow for Object.Destroy calls to finish since we're making copies of some of the object below yield return(null); // ---------- Next load custom silhouette models from our asset bundle ---------- // var silhouetteMaterial = modelRend.material; var res = ResourceUtils.GetEmbeddedResource("silhouettes", typeof(MobAdderPlugin).Assembly); var sab = AssetBundle.LoadFromMemory(res); //var sab = AssetBundle.LoadFromFile(@"E:\Unity projects\kk test\Assets\AssetBundles\test"); var names = sab.GetAllAssetNames(); var uniformNames = names.Where(x => x.Contains("uniform_")).ToList(); _uniformSilhouetteTemplates = new List <GameObject>(); foreach (var uniformName in uniformNames) { var newTop = CreteSilhouetteFromBundle(sab, uniformName, silhouetteMaterial, animObjCopy, ctrl); _uniformSilhouetteTemplates.Add(newTop); } var gymNames = names.Where(x => x.Contains("gym_")).ToList(); _gymSilhouetteTemplates = new List <GameObject>(); foreach (var gymName in gymNames) { var newTop = CreteSilhouetteFromBundle(sab, gymName, silhouetteMaterial, animObjCopy, ctrl); _gymSilhouetteTemplates.Add(newTop); } MobAdderPlugin.Logger.LogInfo($"Loaded {_uniformSilhouetteTemplates.Count} uniform silhouettes and {_gymSilhouetteTemplates.Count} gym silhouettes"); var unused = names.Except(uniformNames).Except(gymNames).ToArray(); if (unused.Any()) { MobAdderPlugin.Logger.LogWarning("Unused assets in the silhouette asset bundle: " + string.Join("; ", unused)); } sab.Unload(false); // Allow for templates to finish creating before allowing spawning them yield return(null); }
public AudioResourceFactory() { _audioSourceContainer = new GameObject(); _audioSourceContainer.name = "AudioSourceContainer"; Object.DontDestroyOnLoad(_audioSourceContainer); }
public static void PlaySound(this MonoBehaviour sfxSource, AudioClip clip, SoundType type = SoundType.Default, Vector3?location = null) { if (sfxSource == null) { sfxSource = _crossfader; } if (clip == null) { Debug.Log(sfxSource.name + " trying to play a null audio clip."); clip = AudioMissing; } AudioSource source; if (_audioSources.Count > 0) { source = _audioSources.Dequeue(); } else { var go = new GameObject("soundEffectDummy"); source = go.AddComponent <AudioSource>(); Object.DontDestroyOnLoad(go); } source.gameObject.SetActive(true); if (location != null) { source.transform.SetParent(_gameObject.transform); source.transform.position = location.Value; } else { source.transform.SetParent(sfxSource.transform); source.transform.localPosition = Vector3.zero; } if (type == SoundType.Default) { AudioDatabase.ClipTypes.TryGetValue(clip, out type); } switch (type) { case SoundType.SoundEffect: source.outputAudioMixerGroup = EffectsMixerGroup; break; case SoundType.Ambience: source.outputAudioMixerGroup = AmbienceMixerGroup; break; case SoundType.Music: source.outputAudioMixerGroup = MusicMixerGroup; break; case SoundType.Interface: source.outputAudioMixerGroup = InterfaceMixerGroup; break; case SoundType.Dialogue: source.outputAudioMixerGroup = DialogueMixerGroup; break; default: source.outputAudioMixerGroup = MasterMixerGroup; break; } source.clip = clip; source.Play(); sfxSource.StartCoroutine(requeueSource(source)); }
public void DontDestroyOnLoad() { Object.DontDestroyOnLoad(go); }
public override void Initialize() { instance = this; instance.Log("Initializing"); float startTime = Time.realtimeSinceStartup; instance.Log("Building MethodInfo dict..."); bindMethods.Clear(); foreach (MethodInfo method in typeof(BindableFunctions).GetMethods(BindingFlags.Public | BindingFlags.Static)) { object[] attributes = method.GetCustomAttributes(typeof(BindableMethod), false); if (attributes.Any()) { BindableMethod attr = (BindableMethod)attributes[0]; string name = attr.name; string cat = attr.category; bindMethods.Add(name, new Pair(cat, method)); } } instance.Log("Done! Time taken: " + (Time.realtimeSinceStartup - startTime) + "s. Found " + bindMethods.Count + " methods"); settings = GlobalSettings; if (settings.FirstRun) { instance.Log("First run detected, setting default binds"); settings.FirstRun = false; settings.binds.Clear(); settings.binds.Add("Toggle All UI", (int)KeyCode.F1); settings.binds.Add("Toggle Info", (int)KeyCode.F2); settings.binds.Add("Toggle Menu", (int)KeyCode.F3); settings.binds.Add("Toggle Console", (int)KeyCode.F4); settings.binds.Add("Force Pause", (int)KeyCode.F5); settings.binds.Add("Hazard Respawn", (int)KeyCode.F6); settings.binds.Add("Set Respawn", (int)KeyCode.F7); settings.binds.Add("Force Camera Follow", (int)KeyCode.F8); settings.binds.Add("Toggle Enemy Panel", (int)KeyCode.F9); settings.binds.Add("Self Damage", (int)KeyCode.F10); settings.binds.Add("Toggle Binds", (int)KeyCode.BackQuote); settings.binds.Add("Nail Damage +4", (int)KeyCode.Equals); settings.binds.Add("Nail Damage -4", (int)KeyCode.Minus); settings.binds.Add("Increase Timescale", (int)KeyCode.KeypadPlus); settings.binds.Add("Decrease Timescale", (int)KeyCode.KeypadMinus); settings.binds.Add("Toggle Hero Light", (int)KeyCode.Home); settings.binds.Add("Toggle Vignette", (int)KeyCode.Insert); settings.binds.Add("Zoom In", (int)KeyCode.PageUp); settings.binds.Add("Zoom Out", (int)KeyCode.PageDown); settings.binds.Add("Reset Camera Zoom", (int)KeyCode.End); settings.binds.Add("Toggle HUD", (int)KeyCode.Delete); settings.binds.Add("Hide Hero", (int)KeyCode.Backspace); } UnityEngine.SceneManagement.SceneManager.activeSceneChanged += LevelActivated; GameObject UIObj = new GameObject(); UIObj.AddComponent <GUIController>(); Object.DontDestroyOnLoad(UIObj); ModHooks.Instance.SavegameLoadHook += LoadCharacter; ModHooks.Instance.NewGameHook += NewCharacter; ModHooks.Instance.BeforeSceneLoadHook += OnLevelUnload; ModHooks.Instance.TakeHealthHook += PlayerDamaged; ModHooks.Instance.ApplicationQuitHook += SaveSettings; BossHandler.PopulateBossLists(); GUIController.Instance.BuildMenus(); Console.AddLine("New session started " + DateTime.Now); }
// sets up all gameobjects needed to render frames, including a mesh with the correct material public TextureRenderer(Texture textureToRender, int renderTextureLayer, QCARRenderer.Vec2I requestedTextureSize) { if (renderTextureLayer > 31) { Debug.LogError("WebCamBehaviour.SetupTextureBufferCamera: configured layer > 31 is not supported by Unity!"); return; } mTextureWidth = requestedTextureSize.x; mTextureHeight = requestedTextureSize.y; float halfMeshHeight = (mTextureHeight / (float)mTextureWidth) * 0.5f; // camera object: GameObject texBufferGameObj = new GameObject("TextureBufferCamera"); mTextureBufferCamera = texBufferGameObj.AddComponent <Camera>(); mTextureBufferCamera.isOrthoGraphic = true; mTextureBufferCamera.orthographicSize = halfMeshHeight; mTextureBufferCamera.aspect = mTextureWidth / (float)mTextureHeight; mTextureBufferCamera.nearClipPlane = 0.5f; mTextureBufferCamera.farClipPlane = 1.5f; mTextureBufferCamera.cullingMask = (1 << renderTextureLayer); mTextureBufferCamera.enabled = false; // camera will only render on demand!! // if the ARCamera should be used across multiple scenes, make sure the texture buffer object does not get destroyed: if (KeepAliveBehaviour.Instance != null && KeepAliveBehaviour.Instance.KeepARCameraAlive) { Object.DontDestroyOnLoad(texBufferGameObj); } // mesh to display the given texture GameObject textureBufferMesh = new GameObject("TextureBufferMesh", new[] { typeof(MeshFilter), typeof(MeshRenderer) }); textureBufferMesh.transform.parent = texBufferGameObj.transform; textureBufferMesh.layer = renderTextureLayer; Mesh mesh = new Mesh { vertices = new[] { new Vector3(-0.5f, halfMeshHeight, 1f), new Vector3(0.5f, halfMeshHeight, 1f), new Vector3(-0.5f, -halfMeshHeight, 1f), new Vector3(0.5f, -halfMeshHeight, 1f), }, uv = new[] { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f), }, triangles = new[] { 0, 1, 2, 2, 1, 3 } }; // renderer and material MeshRenderer meshRenderer = textureBufferMesh.GetComponent <MeshRenderer>(); meshRenderer.material = new Material(Shader.Find("Unlit/Texture")); meshRenderer.material.mainTexture = textureToRender; MeshFilter meshFilter = textureBufferMesh.GetComponent <MeshFilter>(); meshFilter.mesh = mesh; }
private void OnChangeFontByLanguageSetFont(On.ChangeFontByLanguage.orig_SetFont orig, ChangeFontByLanguage self) { orig(self); Log(1); if (Language.Language.CurrentLanguage() == LanguageCode.TH) { Log(2); bool json = true; if (json) { if (fa == null) { Log(3); Assembly asm = Assembly.GetExecutingAssembly(); Log(4); using (Stream s = asm.GetManifestResourceStream("LanguageSupport.Resources.noto_serif_thai_bold.json")) { Log(5); if (s == null) { return; } Log(6); byte[] buffer = new byte[s.Length]; Log(7); s.Read(buffer, 0, buffer.Length); Log(8); s.Dispose(); Log(9); string jsonText = System.Text.Encoding.UTF8.GetString(buffer); Log(10); fa = JsonConvert.DeserializeObject <TMP_FontAsset>(jsonText, new TmpFontConverter()); Log(10.5); fa.name = "noto_serif_thai_bold_tmpro"; Log(11); Object.DontDestroyOnLoad(fa); } fa.atlas = null; // texture2d fa.material = new Material(Shader.Find("GUI/Text Shader")); using (Stream s = asm.GetManifestResourceStream("LanguageSupport.Resources.noto_serif_thai_bold.png")) { if (s != null) { byte[] buffer = new byte[s.Length]; s.Read(buffer, 0, buffer.Length); s.Dispose(); //Create texture from bytes var tex = new Texture2D(2, 2); tex.LoadImage(buffer, true); // Create sprite from texture // Split is to cut off the DreamKing.Resources. and the .png atlas = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f)); Object.DontDestroyOnLoad(atlas); } } fa.material.SetTexture("_MainTex", atlas.texture); fa.atlas = atlas.texture; fa.material.SetColor("_Color", Color.white); } if (fa != null) { Log(20); self.GetAttr <ChangeFontByLanguage, TextMeshPro>("tmpro").font = fa; //var tmp = self.GetAttr<ChangeFontByLanguage, TextMeshPro>("tmpro"); //Log(21); //tmp.font = fa; //Log(22); //self.SetAttr<ChangeFontByLanguage, TextMeshPro>("tmpro", tmp); } } else { if (abFa == null) { Log(12); Assembly asm = Assembly.GetExecutingAssembly(); Log(13); using (Stream s = asm.GetManifestResourceStream("LanguageSupport.Resources.tmprofont")) { Log(14); if (s == null) { return; } Log(15); abFa = AssetBundle.LoadFromStream(s); Log(16); Object.DontDestroyOnLoad(abFa); } } Log(17); if (fa == null && abFa != null) { Log(18); fa = abFa.LoadAsset <TMP_FontAsset>("noto_serif_thai_bold.asset"); Log(18.5); fa.name = "noto_serif_thai_bold_tmpro"; Log(19); Object.DontDestroyOnLoad(fa); } if (fa != null) { Log(20); var tmp = (TextMeshPro)typeof(ChangeFontByLanguage).GetField("tmpro", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(self); Log(21); tmp.font = fa; Log(22); typeof(ChangeFontByLanguage).GetField("tmpro", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(self, tmp); } } } Log(23); }
public override void Invoke(Component target) { Object.DontDestroyOnLoad(target); }
public IEnumerator Revek() { GameObject revek = Object.Instantiate ( ObjectLoader.InstantiableObjects["Revek"], HeroController.instance.gameObject.transform.position, Quaternion.identity ); yield return(new WaitForSecondsRealtime(1)); Object.DontDestroyOnLoad(revek); revek.SetActive(true); PlayMakerFSM ctrl = revek.LocateMyFSM("Control"); // Make sure init gets to run. yield return(null); // Actually spawn. ctrl.SetState("Appear Pause"); // ReSharper disable once ImplicitlyCapturedClosure (ctrl) ctrl.AddAction("Hit", new InvokeMethod(() => Object.Destroy(revek))); // ReSharper disable once ImplicitlyCapturedClosure (ctrl) void OnUnload() { if (revek == null) { return; } revek.SetActive(false); } void OnLoad(Scene a, Scene b) { try { if (revek == null) { return; } revek.SetActive(true); ctrl.SetState("Appear Pause"); } catch { Object.Destroy(revek); } } GameManager.instance.UnloadingLevel += OnUnload; USceneManager.activeSceneChanged += OnLoad; yield return(new WaitForSecondsRealtime(30)); Object.Destroy(revek); GameManager.instance.UnloadingLevel -= OnUnload; USceneManager.activeSceneChanged -= OnLoad; }
public static T DontDestroyOnLoad <T>(this T selfObj) where T : Object { Object.DontDestroyOnLoad(selfObj); return(selfObj); }
/// <summary> /// Initialization method for setting up the simulation network /// </summary> /// <param name="simulationId">This machine simulation id</param> /// <param name="clusterData">Cluster data for this simulation</param> /// <param name="settings">Settings used in this simulation</param> public void Initialize(string simulationId, ClusterData clusterData, NetworkSettings settings) { ClusterData = clusterData; Settings = settings; //Check what cluster node type is this machine in the simulation if (ClusterData.Instances.Length <= 1) { Type = ClusterNodeType.NotClusterNode; } else { //Set this machine type var instancesData = ClusterData.Instances.Where(instance => instance.SimId == simulationId).ToArray(); var resultsCount = instancesData.Length; if (resultsCount == 0) { throw new ArgumentException( $"Invalid cluster settings. Could not find instance data for the simulation id '{simulationId}'."); } if (resultsCount > 1) { throw new ArgumentException( $"Invalid cluster settings. Found multiple instance data for the simulation id '{simulationId}'."); } var thisInstanceData = instancesData[0]; Type = thisInstanceData.IsMaster ? ClusterNodeType.Master : ClusterNodeType.Client; LocalIdentifier = thisInstanceData.SimId; foreach (var ip in thisInstanceData.Ip) { LocalAddresses.Add(new IPEndPoint(IPAddress.Parse(ip), Settings.ConnectionPort)); } //Setup master addresses var masterInstanceData = ClusterData.Instances.Where(instance => instance.IsMaster).ToArray(); resultsCount = masterInstanceData.Length; if (resultsCount == 0) { throw new ArgumentException($"Invalid cluster settings. Could not find master instance data."); } if (resultsCount > 1) { throw new ArgumentException($"Invalid cluster settings. Found multiple master instance data."); } MasterIdentifier = masterInstanceData[0].SimId; foreach (var ip in masterInstanceData[0].Ip) { MasterAddresses.Add(new IPEndPoint(IPAddress.Parse(ip), Settings.ConnectionPort)); } } //Initialize network objects var mainThreadDispatcher = Object.FindObjectOfType <MainThreadDispatcher>(); if (mainThreadDispatcher == null) { var dispatcher = new GameObject("MainThreadDispatcher"); Object.DontDestroyOnLoad(dispatcher); dispatcher.AddComponent <MainThreadDispatcher>(); } if (Type == ClusterNodeType.Master) { var masterGameObject = new GameObject("MasterManager"); Object.DontDestroyOnLoad(masterGameObject); Master = masterGameObject.AddComponent <MasterManager>(); Master.SetSettings(Settings); var clientsIdentifiers = ClusterData.Instances.Where(instanceData => !instanceData.IsMaster) .Select(instanceData => instanceData.SimId).ToList(); Master.StartConnection(clientsIdentifiers); } else if (Type == ClusterNodeType.Client) { var clientGameObject = new GameObject("ClientManager"); Object.DontDestroyOnLoad(clientGameObject); Client = clientGameObject.AddComponent <ClientManager>(); clientGameObject.AddComponent <MainThreadDispatcher>(); Client.SetSettings(Settings); Client.StartConnection(); Client.TryConnectToMaster(); } Log.Info("Initialized the Simulation Network data."); }