public void Dispose() { MonoBehaviour.Destroy(_selfObject); }
/// <summary> /// Validates that required member variables are set and assigns values to the class's private members /// Sets IsInitialized to True if all expected data are present; False otherwise /// </summary> private void Initialize() { this.IsInitialized = true; this.cameraQuaternion = Quaternion.Euler(this.cameraRotation); this.maskScale = Vector3.one; // Validate Inspector fields if (!this.primaryCamera) { Debug.LogError("MagicSplitscreen: Primary Camera is not assigned."); this.IsInitialized = false; } else { // Put the mask just inside the view frustum this.maskOffset = this.primaryCamera.nearClipPlane + 0.1f; } AudioListener cameraListener = this.primaryCamera.GetComponent <AudioListener>() as AudioListener; if (cameraListener) { Debug.Log("MagicSplitscreen: Primary Camera has an AudioListener. It will be removed."); MonoBehaviour.Destroy(cameraListener); } AudioListener[] listeners = GameObject.FindObjectsOfType(typeof(AudioListener)) as AudioListener[]; if (listeners.Length == 0 || (listeners.Length == 1 && listeners[0] == cameraListener)) { if (listeners.Length == 0) { Debug.Log("MagicSplitscreen: Could not find an AudioListener. One will be created."); } else { Debug.Log("MagicSplitscreen: Creating a replacement AudioListener."); } GameObject go = new GameObject(); go.transform.parent = this.transform; go.name = "Audio Listener (MagicSplitscreen)"; this.audioListener = go.AddComponent <AudioListener>(); } else { Debug.LogError("MagicSplitscreen: There are unexpected AudioListeners in the scene. Please remove all but one."); this.IsInitialized = false; } // Set up the splitscreen mask and separator this.isSeparatorUsable = false; this.splitscreenMask = this.GetComponentInChildren <MeshRenderer>(); if (!this.splitscreenMask) { Debug.LogError("MagicSplitscreen: No MeshRenderer mask found in Magic Splitscreen's children."); this.IsInitialized = false; } else { this.maskLayer = this.splitscreenMask.gameObject.layer; this.maskTransform = this.splitscreenMask.transform; MeshRenderer[] renderers = this.splitscreenMask.GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer mr in renderers) { if (mr != this.splitscreenMask) { this.separatorRenderer = mr; break; } } if (!this.separatorRenderer) { Debug.LogWarning("Magic Splitscreen: The separator stripe is missing from the splitscreen mask."); } else { this.separatorMaterial = this.separatorRenderer.material; if (!this.separatorMaterial) { Debug.LogWarning("Magic Splitscreen: The separator stripe does not have a material."); } else { this.isSeparatorUsable = true; } } } this.InitializeCameras(); }
public override void SetupAttributes() { base.SetupAttributes(); blacklistedSkills = new[] { LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/EngiBody/EngiCancelTargetingDummy"), LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/EngiBody/EngiConfirmTargetDummy"), LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/EngiBody/EngiBodyPlaceTurret"), LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/EngiBody/EngiBodyPlaceWalkerTurret"), LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/EngiBody/EngiHarpoons"), LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/CaptainBody/CaptainCancelDummy"), LegacyResourcesAPI.Load <RoR2.Skills.SkillDef>("SkillDefs/CaptainBody/PrepSupplyDrop"), }; var rampTex = Addressables.LoadAssetAsync <Texture2D>("RoR2/Base/Common/ColorRamps/texRampDefault.png") .WaitForCompletion(); var tmpPrefab = LegacyResourcesAPI.Load <GameObject>("Prefabs/NetworkedObjects/HealPack").InstantiateClone("TkSatTempSetupPrefab", false); var wispColor = new Color(0.3f, 0.05f, 0.4f); var vros = tmpPrefab.GetComponent <VelocityRandomOnStart>(); vros.enabled = false; var dstroy = tmpPrefab.GetComponent <DestroyOnTimer>(); dstroy.duration = wispDuration; var blinker = tmpPrefab.GetComponent <BeginRapidlyActivatingAndDeactivating>(); blinker.delayBeforeBeginningBlinking = dstroy.duration - 1f; var trail = tmpPrefab.transform.Find("HealthOrbEffect/TrailParent/Trail").gameObject; var tren = trail.GetComponent <TrailRenderer>(); tren.material.SetTexture("_RemapTex", rampTex); tren.material.SetColor("_TintColor", wispColor); var core = tmpPrefab.transform.Find("HealthOrbEffect/VFX/Core").gameObject; var cren = core.GetComponent <ParticleSystem>(); var ccol = cren.colorOverLifetime; ccol.color = new ParticleSystem.MinMaxGradient(wispColor, wispColor.AlphaMultiplied(0f)); core.transform.localScale *= 0.5f; var pulse = tmpPrefab.transform.Find("HealthOrbEffect/VFX/PulseGlow").gameObject; var pren = pulse.GetComponent <ParticleSystem>(); var pcol = pren.colorOverLifetime; pcol.color = new ParticleSystem.MinMaxGradient(wispColor, wispColor.AlphaMultiplied(0f)); pulse.transform.localScale *= 0.5f; var pickup = tmpPrefab.transform.Find("PickupTrigger").gameObject; pickup.transform.parent = null; GameObject.DestroyImmediate(pickup); var grav = tmpPrefab.transform.Find("GravitationController").gameObject; MonoBehaviour.Destroy(grav.GetComponent <GravitatePickup>()); var gravramp = grav.AddComponent <VoidwispController>(); gravramp.duration = dstroy.duration; gravramp.parentRigidbody = tmpPrefab.GetComponent <Rigidbody>(); gravramp.teamFilter = tmpPrefab.GetComponent <TeamFilter>(); wispPrefab = tmpPrefab.InstantiateClone("TkSatVoidWisp", true); GameObject.Destroy(tmpPrefab); itemDef.requiredExpansion = Addressables.LoadAssetAsync <ExpansionDef>("RoR2/DLC1/Common/DLC1.asset") .WaitForCompletion(); On.RoR2.ItemCatalog.SetItemRelationships += (orig, providers) => { var isp = ScriptableObject.CreateInstance <ItemRelationshipProvider>(); isp.relationshipType = DLC1Content.ItemRelationshipTypes.ContagiousItem; isp.relationships = new[] { new ItemDef.Pair { itemDef1 = PixieTube.instance.itemDef, itemDef2 = itemDef } }; orig(providers.Concat(new[] { isp }).ToArray()); }; }
public static GameObject CreateRosterInfo(GenericShip newShip) { GameObject prefab = (GameObject)Resources.Load("Prefabs/RosterPanel", typeof(GameObject)); int playerPanelNum = (Network.IsNetworkGame && !Network.IsServer) ? AnotherPlayer(newShip.Owner.Id) : newShip.Owner.Id; GameObject newPanel = MonoBehaviour.Instantiate(prefab, GameObject.Find("UI/RostersHolder").transform.Find("TeamPlayer" + playerPanelNum).Find("RosterHolder").transform); //Generic info newPanel.transform.Find("ShipInfo/ShipPilotSkillText").GetComponent <Text>().text = newShip.PilotSkill.ToString(); newPanel.transform.Find("ShipInfo/ShipFirepowerText").GetComponent <Text>().text = newShip.Firepower.ToString(); newPanel.transform.Find("ShipInfo/ShipAgilityText").GetComponent <Text>().text = newShip.Agility.ToString(); newPanel.transform.Find("ShipInfo/ShipHullText").GetComponent <Text>().text = newShip.MaxHull.ToString(); newPanel.transform.Find("ShipInfo/ShipShieldsText").GetComponent <Text>().text = newShip.MaxShields.ToString(); // ALT ShipId text PlayerNo rosterPanelOwner = (Network.IsNetworkGame && !Network.IsServer) ? AnotherPlayer(newShip.Owner.PlayerNo) : newShip.Owner.PlayerNo; newPanel.transform.Find("ShipInfo/ShipId").GetComponent <Text>().text = newShip.ShipId.ToString(); newPanel.transform.Find("ShipIdText/Text").GetComponent <Text>().text = newShip.ShipId.ToString(); newPanel.transform.Find("ShipIdText/Text").GetComponent <Text>().color = (newShip.Owner.PlayerNo == PlayerNo.Player1) ? Color.green : Color.red; newPanel.transform.Find("ShipIdText").localPosition = new Vector3((rosterPanelOwner == PlayerNo.Player1) ? SHIP_PANEL_WIDTH + 5 : -50, 0, 0); newPanel.transform.Find("ShipIdText").gameObject.SetActive(true); //Tooltips GameObject pilotNameGO = newPanel.transform.Find("ShipInfo/ShipPilotNameText").gameObject; pilotNameGO.GetComponent <Text>().text = newShip.PilotName; Tooltips.AddTooltip(pilotNameGO, newShip.ImageUrl); SubscribeSelectionByInfoPanel(pilotNameGO); GameObject shipTypeGO = newPanel.transform.Find("ShipInfo/ShipTypeText").gameObject; shipTypeGO.GetComponent <Text>().text = newShip.Type; Tooltips.AddTooltip(shipTypeGO, newShip.ManeuversImageUrl); SubscribeSelectionByInfoPanel(shipTypeGO); //Mark newPanel.transform.Find("Mark").localPosition = new Vector3((rosterPanelOwner == PlayerNo.Player1) ? SHIP_PANEL_WIDTH - 2 : -8, 0, 0); SubscribeMarkByHover(newPanel); //Hull and shields float panelWidth = SHIP_PANEL_WIDTH - 10; float hullAndShield = newShip.MaxHull + newShip.MaxShields; float panelWidthNoDividers = panelWidth - (1 * (hullAndShield - 1)); float damageIndicatorWidth = panelWidthNoDividers / hullAndShield; GameObject damageIndicatorBar = newPanel.transform.Find("ShipInfo/DamageBarPanel").gameObject; GameObject damageIndicator = damageIndicatorBar.transform.Find("DamageIndicator").gameObject; damageIndicator.GetComponent <RectTransform>().sizeDelta = new Vector2(damageIndicatorWidth, 10); for (int i = 0; i < hullAndShield; i++) { GameObject newDamageIndicator = MonoBehaviour.Instantiate(damageIndicator, damageIndicatorBar.transform); newDamageIndicator.transform.position = damageIndicator.transform.position + new Vector3(i * (damageIndicatorWidth + 1), 0, 0); if (i < newShip.MaxHull) { newDamageIndicator.GetComponent <Image>().color = Color.yellow; newDamageIndicator.name = "DamageIndicator.Hull." + (i + 1).ToString(); } else { newDamageIndicator.GetComponent <Image>().color = new Color(0, 202, 255); newDamageIndicator.name = "DamageIndicator.Shield." + (i - newShip.MaxHull + 1).ToString(); } newDamageIndicator.SetActive(true); } MonoBehaviour.Destroy(damageIndicator); //Assigned Maneuver Dial GameObject maneuverDial = newPanel.transform.Find("AssignedManeuverDial").gameObject; SubscribeShowManeuverByHover(maneuverDial); maneuverDial.transform.localPosition = (rosterPanelOwner == PlayerNo.Player1) ? new Vector3(320, -5, 0) : new Vector3(-120, -5, 0); //Tags newPanel.transform.Find("ShipInfo").tag = "ShipId:" + newShip.ShipId.ToString(); maneuverDial.transform.Find("Holder").gameObject.tag = "ShipId:" + newShip.ShipId.ToString(); //Finish AddToRoster(newShip, newPanel); newPanel.transform.Find("ShipInfo").gameObject.SetActive(true); return(newPanel); }
public override GameObject CreateObject(Transform parent) { FormattedFloatListSettingsValueController baseSetting = MonoBehaviour.Instantiate(Resources.FindObjectsOfTypeAll <FormattedFloatListSettingsValueController>().First(x => (x.name == "VRRenderingScale")), parent, false); baseSetting.name = "BSMLColorSetting"; GameObject gameObject = baseSetting.gameObject; gameObject.SetActive(false); MonoBehaviour.Destroy(baseSetting); ColorSetting colorSetting = gameObject.AddComponent <ColorSetting>(); Transform valuePick = gameObject.transform.Find("ValuePicker"); (valuePick.transform as RectTransform).sizeDelta = new Vector2(13, 0); Button decButton = valuePick.GetComponentsInChildren <Button>().First(); decButton.enabled = false; decButton.interactable = true; GameObject.Destroy(decButton.transform.Find("Icon").gameObject); GameObject.Destroy(valuePick.GetComponentsInChildren <TextMeshProUGUI>().First().gameObject); colorSetting.editButton = valuePick.GetComponentsInChildren <Button>().Last(); GameObject nameText = gameObject.transform.Find("NameText").gameObject; LocalizedTextMeshProUGUI localizedText = ConfigureLocalizedText(nameText); TextMeshProUGUI text = nameText.GetComponent <TextMeshProUGUI>(); text.text = "Default Text"; List <Component> externalComponents = gameObject.AddComponent <ExternalComponents>().components; externalComponents.Add(text); externalComponents.Add(localizedText); gameObject.GetComponent <LayoutElement>().preferredWidth = 90; Image colorImage = Object.Instantiate(Resources.FindObjectsOfTypeAll <Image>().First(x => x.gameObject.name == "ColorImage" && x.sprite?.name == "NoteCircle"), valuePick, false); colorImage.name = "BSMLCurrentColor"; (colorImage.gameObject.transform as RectTransform).anchoredPosition = new Vector2(0, 0); (colorImage.gameObject.transform as RectTransform).sizeDelta = new Vector2(5, 5); (colorImage.gameObject.transform as RectTransform).anchorMin = new Vector2(0.2f, 0.5f); (colorImage.gameObject.transform as RectTransform).anchorMax = new Vector2(0.2f, 0.5f); colorSetting.colorImage = colorImage; Image icon = colorSetting.editButton.transform.Find("Icon").GetComponent <Image>(); icon.name = "EditIcon"; icon.sprite = Utilities.EditIcon; icon.rectTransform.sizeDelta = new Vector2(4, 4); colorSetting.editButton.interactable = true; (colorSetting.editButton.transform as RectTransform).anchorMin = new Vector2(0, 0); colorSetting.modalColorPicker = base.CreateObject(gameObject.transform).GetComponent <ModalColorPicker>(); gameObject.SetActive(true); return(gameObject); }
public void destroy() { MonoBehaviour.Destroy(spawned); }
public bool Land(Vehicle vehicle) { if (vehicleAttached != null && vehicleAttached != vehicle) { return(false); } if (enabled == false) { return(false); } if (canLandAir == false && Vehicle.sVehicleTypes[vehicle.typeName] == Vehicle.VehicleType.Air) { return(false); } if (canLandSurf == false && Vehicle.sVehicleTypes[vehicle.typeName] == Vehicle.VehicleType.Surf) { return(false); } if (canLandSub == false && Vehicle.sVehicleTypes[vehicle.typeName] == Vehicle.VehicleType.Sub) { return(false); } if (Vehicle.sVehicleLandMethods.ContainsKey(vehicle.typeName) == false || Vehicle.sVehicleLandMethods[vehicle.typeName].Any((string value) => value == landMethod) == false) { return(false); } vehicleAttached = vehicle; if (Vector3.Distance(vehicle.transform.position, landStartPoint.position) < approachDistanceThreshold) { vehicleAttached.enabled = false; vehicleAttached.GetComponentsInChildren <LineRenderer>().Any((LineRenderer lr) => { MonoBehaviour.Destroy(lr); return(false); }); vehicleIsLanding = true; vehicleProgress = 0f; return(true); } else { // The aircraft should move towards the start point first. return(false); } }
///<summary>устгана</summary> public static void Destroy(this GameObject a, float t = 0) { MonoBehaviour.Destroy(a, t); }
public static void DoGlow() { foreach (SteamPlayer play in Provider.clients) { if (play.player == Player.player) { continue; } Highlighter Highlighter = play.player.gameObject.GetComponent <Highlighter>(); if ((Global.VisualsEnabled && Global.VisSettings.Glow) && !Global.AllOff && !Hooks.askScreenshot.NeedingSpy) { if (Highlighter == null) { Highlighter = play.player.gameObject.AddComponent <Highlighter>(); } //Deprecated, http://docs.deepdream.games/HighlightingSystem/5.0/#toc9.1upgrading_from_v4.3_to_v5.0 //Highlighter.SeeThroughOn(); //Highlighter.OccluderOn(); //Color blue if in group if (play.player.quests.groupID == Player.player.quests.groupID) { Highlighter.ConstantOnImmediate(Color.blue); } else { Highlighter.ConstantOnImmediate(Color.yellow); } } else if (Highlighter != null) { Highlighter.ConstantOffImmediate(); MonoBehaviour.Destroy(Highlighter); } } if (Global.VisSettings.Items) { foreach (ItemRegion region in ItemManager.regions) { foreach (ItemDrop drop in region.drops) { if (drop.interactableItem.asset is ItemGunAsset) { EItemRarity rar = ((ItemGunAsset)drop.interactableItem.asset).rarity; if (rar == EItemRarity.COMMON || rar == EItemRarity.UNCOMMON || rar == EItemRarity.RARE) { continue; } Highlighter Highlighter = drop.interactableItem.gameObject.GetComponent <Highlighter>(); if (Global.VisualsEnabled && Global.VisSettings.Glow && !Global.AllOff && !Hooks.askScreenshot.NeedingSpy) { if (Highlighter == null) { Highlighter = drop.interactableItem.gameObject.AddComponent <Highlighter>(); } Highlighter.ConstantOnImmediate(Color.white); } else if (Highlighter != null) { Highlighter.ConstantOffImmediate(); MonoBehaviour.Destroy(Highlighter); } } } } } if (Hooks.askScreenshot.NeedingSpy) { System.Threading.Thread.Sleep(85); Hooks.askScreenshot.GlowReady = true; } }
public override void UpdateScreen() { weaponSpawnTimer.Tick(Time.deltaTime); if (weaponSpawnTimer.IsFinished()) { SpawnWeaponbox(); weaponSpawnTimer.Reset(); } //***IF ROUND ENDED AND GAME IS NOT DONE(still rounds left)*** if (DidRoundEnd() && !didGameEnd) { nextGameTimer.Tick(Time.deltaTime); //if canvas is not yet on screen, keep zooming to winner if (nextGameTimer.GetTimePassed() < 2) { CameraScript.ZoomIn(3); } //if score canvas is not created(not null), destroy level and create it if (!IsScoreCanvasOnScreen() && nextGameTimer.GetTimePassed() >= 2) { DestroyLevel(); CreateScoreCanvas(); } //if timer is done spawn next game if (nextGameTimer.IsFinished()) { if (AreAnyRoundsLeft()) { InitNewGame(); } else { didGameEnd = true; //create winner screen/gui } } } //***IF GAME ENDED AND THERE IS A WINNER*** else if (didGameEnd && IsThereAWinner()) { gameWinnerTimer.Tick(Time.deltaTime); if (!IsWinnerCanvasOnScreen()) { soundManagerScript.PlayCheering(); CreateAndInitWinnerCanvas(); } if (gameWinnerTimer.IsFinished()) { DestroyBackground(); MonoBehaviour.Destroy(winnerCanvasObj); confettiSpawner.GetComponent <confettiSpawn>().DestroySpawner(); CameraScript.ResetZoom(); Profile.ClearProfileList(); Screen.ChangeTo(ScreenType.CHARACTER_CHOICE); } } //***IF GAME ENDED AND THERE IS NO WINNER*** else if (didGameEnd && !IsThereAWinner()) { InitNewGame(); didGameEnd = false; } }
/// <inheritdoc/> public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { MonoBehaviour.Destroy(animator.gameObject, 0); }
public override ActionResult Execute(RAIN.Core.AI ai) { MonoBehaviour.Destroy(ai.Body); return(ActionResult.SUCCESS); }
public void Clear() { MonoBehaviour.Destroy(PhysicalToken.gameObject); Token = null; }
public void Destruir() { MonoBehaviour.Destroy(oControlado.GetComponent <CharacterController>()); }
public override void UpdateGolpe(GameObject G) { tempoDecorrido += Time.deltaTime; if (!addView) { GolpePersonagem golpeP = GolpePersonagem.RetornaGolpePersonagem(G, Nome); if (golpeP.TempoDeInstancia > 0) { posInicial = Emissor.UseOEmissor(G, Nome); } AuxiliarDeInstancia.InstancieEDestrua(Nome, posInicial, DirDeREpulsao, TempoDeDestroy); addView = true; } hit = new RaycastHit(); Vector3 ort = Vector3.Cross(DirDeREpulsao, Vector3.up).normalized; float deslocadorInicial = tempoDecorrido > 1 ? tempoDecorrido : 1; float deslocadorFinal = tempoDecorrido < 0.7f ? tempoDecorrido : 0.7f; if (tempoDecorrido < TempoDeDestroy) { Debug.DrawLine(posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao, posInicial + DirDeREpulsao * 25 * deslocadorFinal, Color.red); Debug.DrawLine( posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao + 0.25f * Vector3.up, posInicial + 0.25f * Vector3.up + DirDeREpulsao * 25 * deslocadorFinal, Color.red); Debug.DrawLine( posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao - 0.25f * Vector3.up, posInicial - 0.25f * Vector3.up + DirDeREpulsao * 25 * deslocadorFinal, Color.red); Debug.DrawLine( posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao - 0.25f * ort, posInicial - 0.25f * ort + DirDeREpulsao * 25 * deslocadorFinal, Color.red); if (Physics.Linecast(posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao, posInicial + DirDeREpulsao * 25 * tempoDecorrido, out hit) || Physics.Linecast( posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao - 0.25f * Vector3.up, posInicial - 0.25f * Vector3.up + DirDeREpulsao * 25 * tempoDecorrido, out hit) || Physics.Linecast( posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao - 0.25f * ort, posInicial - 0.25f * ort + DirDeREpulsao * 25 * tempoDecorrido, out hit) || Physics.Linecast( posInicial + 25 * (deslocadorInicial - 1) * DirDeREpulsao + 0.25f * ort, posInicial + 0.25f * ort + DirDeREpulsao * 25 * tempoDecorrido, out hit) ) { if (impactos % 10 == 0) { GameObject Golpe = elementosDoJogo.el.retorna(DoJogo.impactoDeAgua); Object impacto = MonoBehaviour.Instantiate(Golpe, hit.point, Quaternion.identity); MonoBehaviour.Destroy(impacto, 0.5f); if (impactos == 0) { Dano.VerificaDano(hit.transform.gameObject, G, this); } } impactos++; } } }
/// <summary> /// Calculates the best font size for the passed text field to have, considering the /// passed font and how many lines the client wants the text field to be able to hold /// at once. /// </summary> /// <returns></returns> public int ScaleFontSizeToText(Text textField, Font font = null, int linesPerTextbox = 3) { if (font == null) { LoadDefaultFont(); } else { this.font = font; } //Debug.Log("Scaling font size with font " + font.name); // set up a label prefab as a measuring stick GameObject testLabel = CreateTestLabel(); Text labelText = testLabel.GetComponent <Text> (); RectTransform labelRect = testLabel.GetComponent <RectTransform> (); labelRect.SetParent(textField.transform.parent.parent, false); // Using a small font size and seeing how tall the label gets with one line of // text, use that to figure out a good font size for the main text field to use int baseFontSize = 10; labelText.fontSize = baseFontSize; labelText.text = "A"; Canvas.ForceUpdateCanvases(); float baseHeight = labelRect.rect.height; // further preparations to calculate the aforementioned good size RectTransform textRect = textField.rectTransform; float heightLimit = textRect.rect.height; float targetHeightPerLine = heightLimit / linesPerTextbox; float linesFittable = Mathf.Ceil(heightLimit / baseHeight); // with the current font size int resultSize = Mathf.FloorToInt(baseFontSize * (targetHeightPerLine / baseHeight)); // now test that good size... labelText.text = ""; labelText.fontSize = resultSize; for (int i = 0; i < linesPerTextbox - 1; i++) { labelText.text += "A\nA"; } Canvas.ForceUpdateCanvases(); float diffInHeight = labelRect.rect.height - heightLimit; float diffInLines = Mathf.Abs(diffInHeight / targetHeightPerLine); // ^lines taken up int alterationAmount; int passes = 0; // just for debugging float differenceLimit = 0.1f; while (diffInLines >= differenceLimit) // ... and change it as necessary. { // compare the text heights again for a more accurate result labelText.fontSize = resultSize; Canvas.ForceUpdateCanvases(); diffInHeight = labelRect.rect.height - heightLimit; diffInLines = Mathf.Abs(diffInHeight / baseHeight); alterationAmount = Mathf.FloorToInt(diffInLines); //Debug.Log("Pass " + passes + ":\nDiff in lines: " + diffInLines + "\nAlteration amount: " + alterationAmount); // Raise the size? Lower it? if (diffInHeight > 0) { resultSize -= alterationAmount; } else if (diffInHeight < 0) { resultSize += alterationAmount; } passes++; // avoid an infinite loop, cutting our losses if (passes >= 8) { break; } } // Debug.Log ("Adjusted the font size to best fit the textbox with " + passes + " extra passes."); // Debug.Log("Using the simpler, better algorithm, the font size chosen for font " + font.name + " is: " + resultSize); // won't need this anymore! MonoBehaviour.Destroy(labelText.gameObject); return(resultSize); }
private void Listen() { if (_isReadyToRecord) { int positionOfSample = CheckingSpeech(); if (!_isRecord) { if (positionOfSample >= 0) { _endTimeToTalking = Time.time + _recordLength; _workingData = new List <float>(); _positionOfSamplesToPlay = positionOfSample; //if (_positionOfSamplesToPlay - _sampleRate >= 0) //{ // _positionOfSamplesToPlay -= _sampleRate; //} //else //{ // _positionOfSamplesToPlay = _checkingSamples.Length - Mathf.Abs(_positionOfSamplesToPlay - _sampleRate); //} _isRecord = true; if (StartedRecordEvent != null) { StartedRecordEvent(); } return; } } else if (positionOfSample < 0) { if (!_isRecord) { _positionOfSamplesToPlay = _positionOfLastSample; } else { _loopWithoutRecording++; if (_loopWithoutRecording >= _maxLoopWithoutRecord) { _endTimeToTalking = 0; _isRecord = false; _isPlaying = true; _isReadyToRecord = false; _loopWithoutRecording = 0; RecordSound(); if (_createdClip != null) { MonoBehaviour.Destroy(_createdClip); } _createdClip = AudioClip.Create("Speech", _workingData.Count, 1, _sampleRate, false); _createdClip.SetData(_workingData.ToArray(), 0); if (FinishedRecordEvent != null) { FinishedRecordEvent(); } } } } else { _loopWithoutRecording = 0; } } }
public bool Update() { bool retorno = false; switch (estado) { case EncounterState.truqueDeCamera: TruqueDeCamera(); break; case EncounterState.apresentaAdversario: contadorDeTempo += Time.deltaTime; if (apresentaAdv.Apresenta(contadorDeTempo, cam)) { depoisDeTerminarAApresentacao(); } break; case EncounterState.comecaLuta: GameController.g.HudM.ModoCriature(true); ((IA_Agressiva)inimigo.IA).PodeAtualizar = true; manager.CriatureAtivo.Estado = CreatureManager.CreatureState.emLuta; cam.InicializaCameraDeLuta(manager.CriatureAtivo, inimigo.transform); estado = EncounterState.verifiqueVida; break; case EncounterState.verifiqueVida: //GameController.g.HudM.AtualizeHud(manager, inimigo.MeuCriatureBase); VerifiqueVida(); break; case EncounterState.vitoriaNaLuta: if (!apresentaFim.EstouApresentando(treinador)) { RecebePontosDaVitoria(); } break; case EncounterState.VoltarParaPasseio: if (inimigo) { MonoBehaviour.Destroy(inimigo.gameObject); } Debug.Log("treinador = " + treinador); if (!treinador) { cam.FocarBasica(manager.transform, 10, 10); retorno = true; } estado = EncounterState.emEspera; break; case EncounterState.morreuEmLuta: ApresentaDerrota.RetornoDaDerrota R = apresentaDerrota.Update(); if (R != ApresentaDerrota.RetornoDaDerrota.atualizando) { if (R == ApresentaDerrota.RetornoDaDerrota.voltarParaPasseio) { estado = EncounterState.verifiqueVida; } else if (R == ApresentaDerrota.RetornoDaDerrota.deVoltaAoArmagedom) { estado = EncounterState.emEspera; } } break; case EncounterState.passouDeNivel: if (passou.Update()) { estado = EncounterState.VoltarParaPasseio; } break; } return(retorno); }
private void PlanSelfDestruction() { TimeStarted = Time.time; MonoBehaviour.Destroy(this.gameObject, DelaySeconds); }
public void Update() { if (Constance.SPEC_RUNNING == false && Constance.RUNNING == false) { return; } else if (Constance.SPEC_RUNNING == true && this.specSign == false) { return; } if (end == true) { return; } singTime -= Time.deltaTime; if (singTime > 0) { return; } while (alertBlocks.Count > 0) { GameObject gameObject = alertBlocks[0] as GameObject; MonoBehaviour.Destroy(gameObject); alertBlocks.RemoveAt(0); } if (this.attackOne.IsInAttIndex() == true && attacked == false) { Attribute attribute = attackOne.GetAttribute(); for (int i = 0; i < range.Count; i++) { GameObject gameObject = (GameObject)MonoBehaviour.Instantiate(SkillObject_pre); SkillObject skillObject = gameObject.GetComponent <SkillObject>(); skillObject.res = this.skillConfig.res; skillObject.loop = 1; skillObject.transform.localScale = new Vector3(0.5f, 0.5f, 0); // if(i == 0){ // skillObject.sound = skillConfig.sound1; // } skillObject.transform.position = BattleUtils.GridToPosition((Vector2)range[i]); skillObjects.Add(skillObject); ArrayList objects = BattleControllor.GetGameObjectsByPosition((Vector2)range[i]); for (int j = 0; j < objects.Count; j++) { Charactor c = objects[j] as Charactor; if (c.GetType() != this.attackOne.GetType() && c.IsActive() == true) { bool crit = BattleControllor.Crit(skillConfig.crit); float damage = BattleControllor.Attack(attackOne.GetAttribute(), c.GetAttribute(), skillConfig.demageratio, skillConfig.b, crit); c.ChangeHP(damage, crit); // if(skillConfig.sound2 != 0){ // AudioClip ac = Resources.Load<AudioClip>("Audio/Skill/" + skillConfig.sound2); // if(ac != null){ // c.audio.clip = ac; // c.audio.Play(); // } // } if (c.GetAttribute().hp > 0) { c.PlayAttacked(); } else { c.PlayDead(); } } } } attacked = true; } if (attacked == false) { return; } if (attacked == false) { return; } for (int i = 0; i < skillObjects.Count; i++) { SkillObject skillObject = skillObjects[i] as SkillObject; if (skillObject.IsSpritePlayEnd() == true) { MonoBehaviour.Destroy(skillObject.gameObject); skillObjects.Remove(skillObjects); end = true; this.attackOne.SetPlayLock(false); } } }
public static void Dismiss(ModalDialog dialog) { MonoBehaviour.Destroy(dialog.gameObject); }
public static void ObjectSetup(GameObject go, VectorLine line, Visibility visibility, Brightness brightness, bool makeBounds) { var vc = go.GetComponent(typeof(VisibilityControl)) as VisibilityControl; var vcs = go.GetComponent(typeof(VisibilityControlStatic)) as VisibilityControlStatic; var vca = go.GetComponent(typeof(VisibilityControlAlways)) as VisibilityControlAlways; var bc = go.GetComponent(typeof(BrightnessControl)) as BrightnessControl; if (visibility == Visibility.None) { if (vc) { MonoBehaviour.Destroy(vc); } if (vcs) { MonoBehaviour.Destroy(vcs); } if (vca) { MonoBehaviour.Destroy(vca); } } if (visibility == Visibility.Dynamic) { if (vc == null) { vc = go.AddComponent(typeof(VisibilityControl)) as VisibilityControl; vc.Setup(line, makeBounds); if (bc != null) { bc.SetUseLine(false); } } } else if (visibility == Visibility.Static) { if (vcs == null) { vcs = go.AddComponent(typeof(VisibilityControlStatic)) as VisibilityControlStatic; vcs.Setup(line, makeBounds); if (bc != null) { bc.SetUseLine(false); } } } else if (visibility == Visibility.Always) { if (vca == null) { vca = go.AddComponent(typeof(VisibilityControlAlways)) as VisibilityControlAlways; vca.Setup(line); if (bc != null) { bc.SetUseLine(false); } } } if (brightness == Brightness.Fog) { if (bc == null) { bc = go.AddComponent(typeof(BrightnessControl)) as BrightnessControl; if (vc == null && vcs == null && vca == null) { bc.Setup(line, true); } else { bc.Setup(line, false); } } } else { if (bc) { MonoBehaviour.Destroy(bc); } } }
protected override void _OnDespawn() { base._OnDespawn(); MonoBehaviour.Destroy(this); //destroy this MB after despawn }
private IEnumerator ShapeWipe(Camera cam1, Camera cam2, float time, ZoomType zoom, Mesh mesh, float rotateAmount) { isWorking = true; if (shapeMaterial.Value == null) { shapeMaterial.Value = new Material(Shader.Find("Custom/DepthMask")); } if (!shape) { GameObject gobjShape = new GameObject("Shape"); gobjShape.AddComponent <MeshFilter>(); gobjShape.AddComponent <MeshRenderer>(); gobjShape.GetComponent <Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; gobjShape.GetComponent <Renderer>().receiveShadows = false; shape = gobjShape.transform; shape.GetComponent <Renderer>().material = shapeMaterial.Value; } CameraSetup(cam1, cam2, true, false); Camera useCam = (zoom == ZoomType.Shrink) ? cam1 : cam2; Camera otherCam = (zoom == ZoomType.Shrink) ? cam2 : cam1; float originalDepth = otherCam.depth; CameraClearFlags originalClearFlags = otherCam.clearFlags; otherCam.depth = useCam.depth + 1; otherCam.clearFlags = CameraClearFlags.Depth; shape.gameObject.SetActive(true); (shape.GetComponent <MeshFilter> () as MeshFilter).mesh = mesh; shape.position = otherCam.transform.position + otherCam.transform.forward * (otherCam.nearClipPlane + .01f); shape.parent = otherCam.transform; shape.localRotation = Quaternion.identity; if (useCurve.Value) { float rate = 1.0f / time; if (zoom == ZoomType.Shrink) { for (float i = 1.0f; i > 0.0f; i -= Time.deltaTime * rate) { float t = curve.curve.Evaluate(i); shape.localScale = new Vector3(t, t, t); shape.localEulerAngles = new Vector3(0.0f, 0.0f, i * rotateAmount); yield return(0); } } else { for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate) { float t = curve.curve.Evaluate(i); shape.localScale = new Vector3(t, t, t); shape.localEulerAngles = new Vector3(0.0f, 0.0f, -i * rotateAmount); yield return(0); } } } else { float rate = 1.0f / time; if (zoom == ZoomType.Shrink) { for (float i = 1.0f; i > 0.0f; i -= Time.deltaTime * rate) { float t = Mathf.Lerp(1.0f, 0.0f, Mathf.Sin((1.0f - i) * Mathf.PI * 0.5f)); shape.localScale = new Vector3(t, t, t); shape.localEulerAngles = new Vector3(0.0f, 0.0f, i * rotateAmount); yield return(0); } } else { for (float i = 0.0f; i < 1.0f; i += Time.deltaTime * rate) { float t = Mathf.Lerp(1.0f, 0.0f, Mathf.Sin((1.0f - i) * Mathf.PI * 0.5f)); shape.localScale = new Vector3(t, t, t); shape.localEulerAngles = new Vector3(0.0f, 0.0f, -i * rotateAmount); yield return(0); } } } otherCam.clearFlags = originalClearFlags; otherCam.depth = originalDepth; CameraCleanup(cam1, cam2); shape.parent = null; shape.gameObject.SetActive(false); if (destroyMesh.Value == true) { MonoBehaviour.Destroy(shape.gameObject); } isWorking = false; if (isWorking == false) { inProgress.Value = false; Finish(); } }
internal IEnumerator Start() { UnityWebRequestAsyncOperation webRequestOperation; if (this.method == HttpMethod.GET) { string urlParams = this.url.AbsoluteUri.Contains("?") ? "&" : "?"; if (this.formData != null) { foreach (KeyValuePair <string, string> pair in this.formData) { urlParams += string.Format("{0}={1}&", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value)); } } UnityWebRequest webRequest = UnityWebRequest.Get(url + urlParams); if (Constants.CurrentPlatform != FacebookUnityPlatform.WebGL) { webRequest.SetRequestHeader("User-Agent", Constants.GraphApiUserAgent); } webRequestOperation = webRequest.SendWebRequest(); } else { // POST or DELETE if (this.query == null) { this.query = new WWWForm(); } if (this.method == HttpMethod.DELETE) { this.query.AddField("method", "delete"); } if (this.formData != null) { foreach (KeyValuePair <string, string> pair in this.formData) { this.query.AddField(pair.Key, pair.Value); } } if (Constants.CurrentPlatform != FacebookUnityPlatform.WebGL) { this.query.headers["User-Agent"] = Constants.GraphApiUserAgent; } UnityWebRequest webRequest = UnityWebRequest.Post(url.AbsoluteUri, query); webRequestOperation = webRequest.SendWebRequest(); } yield return(webRequestOperation); if (this.callback != null) { this.callback(new GraphResult(webRequestOperation)); } // after the callback is called, web request should be able to be disposed webRequestOperation.webRequest.Dispose(); MonoBehaviour.Destroy(this); }
/** * <summary> * Remove tank weapon * </summary> * * <returns> * void * </returns> */ public void RemoveWeapon() { this.parts[0] = null; MonoBehaviour.Destroy(this.top); }
internal static void OnDestroyObject(ulong networkId, bool destroyGameObject) { if (NetworkingManager.Singleton == null) { return; } //Removal of spawned object if (!SpawnedObjects.ContainsKey(networkId)) { return; } if (!SpawnedObjects[networkId].IsOwnedByServer && !SpawnedObjects[networkId].IsPlayerObject && NetworkingManager.Singleton.ConnectedClients.ContainsKey(SpawnedObjects[networkId].OwnerClientId)) { //Someone owns it. for (int i = NetworkingManager.Singleton.ConnectedClients[SpawnedObjects[networkId].OwnerClientId].OwnedObjects.Count - 1; i > -1; i--) { if (NetworkingManager.Singleton.ConnectedClients[SpawnedObjects[networkId].OwnerClientId].OwnedObjects[i].NetworkId == networkId) { NetworkingManager.Singleton.ConnectedClients[SpawnedObjects[networkId].OwnerClientId].OwnedObjects.RemoveAt(i); } } } SpawnedObjects[networkId].IsSpawned = false; if (NetworkingManager.Singleton != null && NetworkingManager.Singleton.IsServer) { if (NetworkingManager.Singleton.NetworkConfig.RecycleNetworkIds) { releasedNetworkObjectIds.Enqueue(new ReleasedNetworkId() { NetworkId = networkId, ReleaseTime = Time.unscaledTime }); } if (SpawnedObjects[networkId] != null) { using (PooledBitStream stream = PooledBitStream.Get()) { using (PooledBitWriter writer = PooledBitWriter.Get(stream)) { writer.WriteUInt64Packed(networkId); InternalMessageSender.Send(MLAPIConstants.MLAPI_DESTROY_OBJECT, "MLAPI_INTERNAL", stream, SecuritySendFlags.None, SpawnedObjects[networkId]); } } } } GameObject go = SpawnedObjects[networkId].gameObject; if (destroyGameObject && go != null) { if (customDestroyHandlers.ContainsKey(SpawnedObjects[networkId].PrefabHash)) { customDestroyHandlers[SpawnedObjects[networkId].PrefabHash](SpawnedObjects[networkId]); SpawnManager.OnDestroyObject(networkId, false); } else { MonoBehaviour.Destroy(go); } } SpawnedObjects.Remove(networkId); for (int i = SpawnedObjectsList.Count - 1; i > -1; i--) { if (SpawnedObjectsList[i].NetworkId == networkId) { SpawnedObjectsList.RemoveAt(i); } } }
/** * <summary> * Remove tank body frame * </summary> * * <returns> * void * </returns> */ public void RemoveBody() { this.parts[1] = null; MonoBehaviour.Destroy(this.body); }
public void destroy() { MonoBehaviour.Destroy(controller.gameObject); }
// PLANNING public override GameObject[] PlanMovement() { //Temporary MovementTemplates.ApplyMovementRuler(TheShip); GameObject[] result = new GameObject[101]; float distancePart = ProgressTarget / 80; Vector3 position = TheShip.GetPosition(); GameObject lastShipStand = null; for (int i = 0; i <= 80; i++) { float step = (float)i * distancePart; GameObject prefab = (GameObject)Resources.Load(TheShip.ShipBase.TemporaryPrefabPath, typeof(GameObject)); GameObject ShipStand = MonoBehaviour.Instantiate(prefab, position, TheShip.GetRotation(), BoardTools.Board.GetBoard()); Renderer[] renderers = ShipStand.GetComponentsInChildren <Renderer>(); if (!DebugManager.DebugMovement) { foreach (var render in renderers) { render.enabled = false; } } if (i > 0) { float turningDirection = (Direction == ManeuverDirection.Right) ? 1 : -1; ShipStand.transform.RotateAround(TheShip.TransformPoint(new Vector3(turningAroundDistance * turningDirection, 0, 0)), new Vector3(0, 1, 0), turningDirection * step); UpdatePlanningRotation(ShipStand); if (i == 80) { lastShipStand = ShipStand; } } result[i] = ShipStand; ShipStand.name = "Main" + i; } GameObject savedShipStand = MonoBehaviour.Instantiate(lastShipStand); savedShipStand.transform.localEulerAngles -= new Vector3(0f, lastPlanningRotation, 0f); position = lastShipStand.transform.position; distancePart = TheShip.ShipBase.GetShipBaseDistance() / 20; for (int i = 1; i <= 20; i++) { position = Vector3.MoveTowards(position, position + savedShipStand.transform.TransformDirection(Vector3.forward), distancePart); GameObject prefab = (GameObject)Resources.Load(TheShip.ShipBase.TemporaryPrefabPath, typeof(GameObject)); GameObject ShipStand = MonoBehaviour.Instantiate(prefab, position, savedShipStand.transform.rotation, BoardTools.Board.GetBoard()); Renderer[] renderers = ShipStand.GetComponentsInChildren <Renderer>(); if (!DebugManager.DebugMovement) { foreach (var render in renderers) { render.enabled = false; } } UpdatePlanningRotationFinisher(ShipStand); result[i + 80] = ShipStand; ShipStand.name = "Finishing" + i; } MonoBehaviour.Destroy(savedShipStand); MovementTemplates.HideLastMovementRuler(); return(result); }