public static void Create(Vector3 pos, string text, ColorRgba color) { GameObject pe = new GameObject(GameRes.Data.Prefabs.PowerupEffect_Prefab); pe.GetComponent<PowerupEffect>().Text = text; pe.GetComponent<TextRenderer>().ColorTint = color; pe.Transform.Pos = pos; Scene.Current.RegisterObj(pe); }
public DropDownListButton(GameObject btnObj) { gameobject = btnObj; rectTransform = btnObj.GetComponent<RectTransform>(); btnImg = btnObj.GetComponent<Image>(); btn = btnObj.GetComponent<Button>(); txt = rectTransform.FindChild("Text").GetComponent<Text>(); img = rectTransform.FindChild("Image").GetComponent<Image>(); }
public void OnJoinMatch(GameObject script) { string server_Name = script.GetComponent<MainMenuButtons_script> ().roomNameJoin; string server_Password = script.GetComponent<MainMenuButtons_script> ().roomPasswordJoin; foreach (var match in manager.matches) { if (match.name == server_Name) { manager.matchMaker.JoinMatch (match.networkId, server_Password, manager.OnMatchJoined); } } }
float timer; // Timer for counting up to the next attack. void Awake() { // Setting up the references. player = GameObject.FindGameObjectWithTag("Player"); sentry = GameObject.FindGameObjectWithTag("Sentry"); playerHealth = player.GetComponent <PlayerHealth> (); sentryHealth = sentry?.GetComponent <SentryHealth>(); sentryComp = sentry?.GetComponent <Sentry>(); enemyHealth = GetComponent <EnemyHealth>(); anim = GetComponent <Animator> (); }
void SetupUI() { GameObject go = GameObject.Find("MyView"); // myView = go.AddComponent<VideoSurface>(); // myView.GetComponent<VideoSurface>().EnableFlipTextureApply(true, true); go = GameObject.Find("LeaveButton"); go?.GetComponent <Button>()?.onClick.AddListener(Leave); go = GameObject.Find("JoinButton"); go?.GetComponent <Button>()?.onClick.AddListener(Join); }
public void ScareGhosts() { scared = true; blinky?.GetComponent <GhostMove>().Frighten(); pinky?.GetComponent <GhostMove>().Frighten(); inky?.GetComponent <GhostMove>().Frighten(); clyde?.GetComponent <GhostMove>().Frighten(); _timeToCalm = Time.time + scareLength; Debug.Log("Ghosts Scared"); }
private void Start() { AmbitionApp.Subscribe <string>(GameMessages.LOAD_SCENE, HandleScene); AmbitionApp.Subscribe(GameMessages.FADE_OUT_COMPLETE, HandleFadeOut); AmbitionApp.Subscribe(GameMessages.FADE_IN_COMPLETE, HandleFadeIn); AmbitionApp.SendMessage(GameMessages.FADE_IN); SceneView start = SceneObject?.GetComponent <SceneView>(); (start as Util.IInitializable)?.Initialize(); }
void Update() { HandleInteractions(); onUpdate?.Invoke(this); _currentScreen?.GetComponent <TerminalBehavior>()?.OnScreenUpdate(this); if (_booted) { _effectIntensity = Mathf.Clamp(_effectIntensity - effectRate, -3.0F, 1.0F); ApplyEffects(_effectIntensity); } }
private void Update() { _time = Mathf.Clamp(_time + Time.deltaTime * _direction, 0.0f, SecondsToOpen); _rectTransform.sizeDelta = new Vector2( Mathf.Lerp(_closedSize, _openedSize, _time / SecondsToOpen), _rectTransform.sizeDelta.y); if (IsOpened()) { if (!closing) { List <IInventoryPanelEventHandler> handlers = GameObjectFindHelper.FindGameObjectWithInterface <IInventoryPanelEventHandler>(); ExecuteEventHelper.BroadcastEvent(handlers, (handler, eventData) => { handler.InventoryPanelOpened(); }); closing = true; } Vector2Int slotPosition = _selectedSlot != null ? _selectedSlot.gridPosition : Vector2Int.zero; if (Input.GetKeyDown(KeyCode.W)) { slotPosition.x = Math.Min(Math.Max(slotPosition.x - 1, 0), 1); } else if (Input.GetKeyDown(KeyCode.S)) { slotPosition.x = Math.Min(Math.Max(slotPosition.x + 1, 0), 1); } else if (Input.GetKeyDown(KeyCode.A)) { slotPosition.y = Math.Min(Math.Max(slotPosition.y - 1, 0), 7); } else if (Input.GetKeyDown(KeyCode.D)) { slotPosition.y = Math.Min(Math.Max(slotPosition.y + 1, 0), 7); } else if (Input.GetKeyDown(KeyCode.Space)) { } SelectSlot(transform.Find(String.Format("InventorySlot[{0}][{1}]", slotPosition.x, slotPosition.y) ).GetComponent <InventoryPanelSlot>() ); } else if (closing && IsClosed()) { informationPanel?.GetComponent <ItemInformationPanel>().Hide(); List <IInventoryPanelEventHandler> handlers = GameObjectFindHelper.FindGameObjectWithInterface <IInventoryPanelEventHandler>(); ExecuteEventHelper.BroadcastEvent(handlers, (handler, eventData) => { handler.InventoryPanelClosed(); }); closing = false; } }
private static CollisionPoint FindCollisionPoint(GameObject gameObject, GameObject other, Vector2 oldPosition, Vector2 newPosition) { if (gameObject.GetComponent<Collider>() is CircleCollider){ if (other.GetComponent<Collider>() is CircleCollider) { CircleCollider objCollider = (CircleCollider) gameObject.GetComponent<Collider>(); CircleCollider otherCollider = (CircleCollider) other.GetComponent<Collider>(); float distance = Vector2.Distance(newPosition, other.Position); if (distance < objCollider.Radius + otherCollider.Radius) { return new CollisionPoint(oldPosition); } } else if (other.GetComponent<Collider>() is SquareCollider) { CircleCollider objCollider = (CircleCollider)gameObject.GetComponent<Collider>(); SquareCollider otherCollider = (SquareCollider)other.GetComponent<Collider>(); float distanceX = other.Position.X - newPosition.X; float distanceY = other.Position.Y - newPosition.Y; bool xCollision = Math.Abs(distanceX) < otherCollider.Width/2 + objCollider.Radius; bool yCollision = Math.Abs(distanceY) < otherCollider.Height / 2 + objCollider.Radius; if (xCollision && yCollision) { float xMove = newPosition.X - oldPosition.X; float yMove = newPosition.Y - oldPosition.Y; if (oldPosition.X + objCollider.Radius < other.Position.X - otherCollider.Width/2 || oldPosition.X - objCollider.Radius > other.Position.X + otherCollider.Width / 2) { oldPosition.Y += yMove; //newPosition = new Vector2(0f, oldPosition.Y + yMove); } if (oldPosition.Y + objCollider.Radius < other.Position.Y - otherCollider.Height / 2 || oldPosition.Y - objCollider.Radius > other.Position.Y + otherCollider.Height / 2) { oldPosition.X += xMove; //newPosition.X += oldPosition.X + xMove; //newPosition = new Vector2(oldPosition.X + xMove, 0f); } return new CollisionPoint(oldPosition); } } } return null; }
public void GlowMeUpScotty() { gameObject.GetComponent <Image>().sprite = glowed_up; if (expand_on_glowup) { gameObject.transform.localScale = new Vector3(2, 2, 1); } if (optional_propagate_glow != null) { optional_propagate_glow?.GetComponent <MemeArrowScript>().GlowMeUpScotty(); } }
[Test] public void CloneGameObject() { Random rnd = new Random(); GameObject source = new GameObject("ObjectA"); source.AddComponent(new TestComponent(rnd)); GameObject target = source.DeepClone(); Assert.AreNotSame(source, target); Assert.AreEqual(source.Name, target.Name); Assert.AreEqual(source.GetComponent<TestComponent>(), target.GetComponent<TestComponent>()); Assert.AreNotSame(source.GetComponent<TestComponent>(), target.GetComponent<TestComponent>()); Assert.AreNotSame(source.GetComponent<TestComponent>().TestReferenceList, target.GetComponent<TestComponent>().TestReferenceList); }
/// <summary> /// Checks the component's setup and initializes it /// </summary> protected override void Awake() { if (configurationWindow == null) { SpecialDebugMessages.LogMissingReferenceError(this, nameof(configurationWindow)); } configurationWindowInterface = configurationWindow?.GetComponent <IWindow>(); if (configurationWindowInterface == null) { SpecialDebugMessages.LogComponentNotFoundError(this, nameof(IWindow), configurationWindow); } base.Awake(); }
private void UpdateTargeting(bool action) { FindNextTarget(); var currentProblem = currentTarget?.GetComponent <Problem>(); if (currentProblem != null && action) { if (repairProgress == 0) { repairProgress = 100f; } else { repairProgress -= currentProblem.repairAmount * Time.deltaTime; } repairBar.transform.localScale = new Vector3(repairProgress / 100f, 0.1f, 1f); if (repairProgress <= 0) { Destroy(currentTarget); currentTarget = null; } } else { repairProgress = 0; repairBar.transform.localScale = Vector3.zero; } if (currentTarget != null && action) { var targetDirection = Vector2.SignedAngle(currentTarget.transform.position - transform.position, Vector2.up); if (targetDirection >= -45 && targetDirection <= 45) { animator.SetInteger("direction", (int)Direction.UP); } else if (targetDirection >= 180 - 45 && targetDirection <= 180 + 45) { animator.SetInteger("direction", (int)Direction.DOWN); } else if (targetDirection > 0) { animator.SetInteger("direction", (int)Direction.RIGHT); } else { animator.SetInteger("direction", (int)Direction.LEFT); } } }
// void SetDebugCanvasSize() { // Set the reference canvas size to the actual canvas size, because scale widht/height isn't always ideal Canvas canvas = DebugCanvas?.GetComponent <Canvas>(); CanvasScaler canvasScaler = DebugCanvas?.GetComponent <CanvasScaler>(); if (canvas != null && canvasScaler != null) { int d = canvas.targetDisplay; int Horizontal = Display.displays[d].renderingWidth; int Vertical = Display.displays[d].renderingHeight; canvasScaler.referenceResolution = new Vector2(Horizontal, Vertical); } }
void SetPickObject(GameObject obj) { if (IsItemPicked) { PickItemImageComponent.TryMouseRelease(); } if (IsPurchaseOrderPicked) { PickPurchaseOrderComponent.TryMouseRelease(); } PickItemImageComponent = null; PickPurchaseOrderComponent = null; PickObject = null; if (obj == null) { return; } var order = obj?.GetComponent <PurchaseOrderScript>(); if (order != null) { if (order.TryMousePick()) { PickPurchaseOrderComponent = order; PickObject = obj; return; } } var img = obj?.GetComponent <ItemImage>(); if (img != null) { if (img.TryMousePick()) { PickObject = obj; PickItemImageComponent = img; return; } } return; }
public void OnStart() { GameObject panel = GameObject.GetGameObjectByName("PuzzleButton1").transform.GetChild(0).gameObject; panel1 = GetScript<BoobyTrapDeactivator>(panel); panel = GameObject.GetGameObjectByName("PuzzleButton2").transform.GetChild(0).gameObject; panel2 = GetScript<BoobyTrapDeactivator>(panel); panel = GameObject.GetGameObjectByName("PuzzleButton3").transform.GetChild(0).gameObject; panel3 = GetScript<BoobyTrapDeactivator>(panel); panel = GameObject.GetGameObjectByName("PuzzleButton4").transform.GetChild(0).gameObject; panel4 = GetScript<BoobyTrapDeactivator>(panel); trapLightW = GameObject.GetGameObjectByName("TrapLightW"); trapLightR1 = GameObject.GetGameObjectByName("TrapLightR1"); trapLightR1script = GetScript<PulsingLightScript>(trapLightR1); trapLightR2 = GameObject.GetGameObjectByName("TrapLightR2"); trapLightR2script = GetScript<PulsingLightScript>(trapLightR2); trapLightR3 = GameObject.GetGameObjectByName("TrapLightR3"); trapLightR3script = GetScript<PulsingLightScript>(trapLightR3); trapLightR4 = GameObject.GetGameObjectByName("TrapLightR4"); trapLightR4script = GetScript<PulsingLightScript>(trapLightR4); poisonGas = GameObject.GetGameObjectByName("TSR_PoisonGas"); gas = poisonGas.GetComponent<CParticleEmitter>(); gasScript = GetScript<TransformRiserScript>(poisonGas); GameObject boobyControllerObj = GameObject.GetGameObjectByName("TSR_TrapController");//trapControllerName); controllerScript = GetScript<BoobyTrapDeactivatorController>(boobyControllerObj); gasTimerShutdown = gas.mEmitterProperty.mMaxLifetime; mSound = gameObject.RequireComponent<CSound>(); }
private static void UpdateLobbyControls(NetworkUser exceptUser = null) { var interactable = SteamworksLobbyManager.isInLobby == SteamworksLobbyManager.ownsLobby && File.Exists(SaveFileMetadata.GetCurrentLobbySaveMetadata(exceptUser)?.FilePath); try { if (lobbyButton) { var component = lobbyButton?.GetComponent <HGButton>(); if (component) { component.interactable = interactable; } } } catch { } try { if (lobbyGlyphAndDescription) { var color = interactable ? Color.white : new Color(0.3F, 0.3F, 0.3F); var glyphText = lobbyGlyphAndDescription.transform.GetChild(0).GetComponent <HGTextMeshProUGUI>(); glyphText.color = color; var descriptionText = lobbyGlyphAndDescription.transform.GetChild(1).GetComponent <HGTextMeshProUGUI>(); descriptionText.color = color; } } catch { } }
public static string GetFoodValue(string itemLocation) { if (string.IsNullOrEmpty(itemLocation)) { return("No location"); } StringBuilder sb = new StringBuilder(); GameObject OriginalFabricator = Resources.Load <GameObject>(itemLocation); GameObject prefab = GameObject.Instantiate(OriginalFabricator); var eatable = prefab?.GetComponent <Eatable>(); if (eatable != null) { sb.Append("{"); sb.Append(Environment.NewLine); sb.Append($"\"Name\":\"{eatable.name}\","); sb.Append(Environment.NewLine); sb.Append($"\"WaterValue\":{eatable.GetWaterValue()},"); sb.Append(Environment.NewLine); sb.Append($"\"FoodValue\":{eatable.GetFoodValue()},"); sb.Append(Environment.NewLine); sb.Append($"\"kDecayRate\":{eatable.kDecayRate},"); sb.Append(Environment.NewLine); sb.Append("}"); } return(sb.ToString()); }
private void Awake() { character = GetComponent <Character>(); character.OnReceiveDamageCharacter += AnimateReceiveDamageText; character.OnStartReload += (x) => { StartCoroutine(StartReloading(x)); }; character.gameInfo.OnGameStart += () => { StopCoroutine("StartReloading"); FinishReloading(); }; mainCamera = Camera.main; //Global receivedDmgText = transform.Find("ReceivedDmg").gameObject; receivedDmgTextStartPosition = receivedDmgText.transform.localPosition; healthBarObj = transform.Find("HPBAR").gameObject; healthBarObj.transform.GetChild(0).GetComponent <SpriteRenderer>().material = linearFill; healthBarMaterial = healthBarObj.transform.GetChild(0).GetComponent <SpriteRenderer>().material; nameHolderObj = transform.Find("NameHolder").gameObject; //Player Only aimIndicator = transform.Find("AimIndicator").gameObject; reloadSpriteObj = transform.Find("Reload").gameObject; reloadSpriteObj.GetComponent <SpriteRenderer>().material = radialFill; reloadSpriteMaterial = reloadSpriteObj?.GetComponent <SpriteRenderer>().material; reloadSpriteObj.SetActive(false); receivedDmgText.SetActive(false); }
void Update() { if (ModComponentMain.Settings.instance.disableRandomItemSpawns) { return; } if (this.ItemNames is null || this.ItemNames.Length == 0) { Logger.LogWarning("'{0}' had an invalid list of potential spawn items.", this.name); Destroy(this.gameObject); return; } int index = RandomUtils.Range(0, this.ItemNames.Length); GameObject prefab = Resources.Load(this.ItemNames[index])?.Cast <GameObject>(); if (prefab is null) { Logger.LogWarning("Could not use '{0}' to spawn random item '{1}'", this.name, this.ItemNames[index]); Destroy(this.gameObject); return; } GameObject gear = Instantiate(prefab, this.transform.position, this.transform.rotation); gear.name = prefab.name; DisableObjectForXPMode xpmode = gear?.GetComponent <DisableObjectForXPMode>(); if (xpmode != null) { Destroy(xpmode); } Destroy(this.gameObject); }
public IAvatarBody Create(CreateAvatarBodyArgs args) { DiContainer subContainer = _container.CreateSubContainer(); subContainer.BindInstance(args); GameObject obj = null; switch (args.BodyType) { case (byte)'A': obj = subContainer.InstantiatePrefab(_bodyPrefabA); break; case (byte)'B': obj = subContainer.InstantiatePrefab(_bodyPrefabB); break; default: Debug.LogError($"The passed body type is not found. Received body type is {args.BodyType}"); break; } return(obj?.GetComponent <IAvatarBody>()); }
private static float fActiveModeHealthRegenMultiplier = 5f; // Health regeneration is multiplied by this amount in active mode protected void Start() { string RCFilename; if (thermalReactorCharge is null && PrefabDatabase.TryGetPrefabFilename(CraftData.GetClassIdForTechType(TechType.Exosuit), out RCFilename)) { AddressablesUtility.LoadAsync <GameObject>(RCFilename).Completed += (x) => { GameObject gameObject1 = x.Result; Exosuit exosuit = gameObject1?.GetComponent <Exosuit>(); thermalReactorCharge = exosuit?.thermalReactorCharge; }; } if (sonarSound is null && PrefabDatabase.TryGetPrefabFilename(CraftData.GetClassIdForTechType(TechType.Seamoth), out RCFilename)) { AddressablesUtility.LoadAsync <GameObject>(RCFilename).Completed += (x) => { GameObject gameObject1 = x.Result; SeaMoth seamoth = gameObject1?.GetComponent <SeaMoth>(); if (seamoth?.sonarSound != null) { sonarSound = this.gameObject.AddComponent <FMOD_CustomEmitter>(); sonarSound.SetAsset(seamoth.sonarSound.asset); sonarSound.UpdateEventAttributes(); } foreach (var r in gameObject1.GetComponentsInChildren <Renderer>()) { } }; } }
private void CmdApplyItem(GameObject sourceItemGo, GameObject interactableGo) { Item.Item sourceItem = sourceItemGo?.GetComponent <Item.Item>(); IPlayerInteractable interactable = interactableGo.GetComponent <IPlayerInteractable>(); interactable?.ApplyItemServer(sourceItem); }
private void checkSRCdata() { //_targetObject = _targetSurfaceBind.value as GameObject; //_preData = _preDataBind.value as PreDataSO; //_spawnSO = _spawnSObind.value as SpawnSO; _currentEditSpawnZone = -1; bool res = true; MeshFilter mf = null; if (_targetObject == null) { res = false; } else { mf = _targetObject?.GetComponent <MeshFilter>(); } if (mf == null || mf.sharedMesh == null) { res = false; } if (res && (_preData == null || mf.sharedMesh.triangles.Length != _preData.trilinks.Length || mf.sharedMesh.vertexCount != _preData.trisAroundVertex.Length)) { res = false; } if (res && _spawnSO == null) { res = false; } prepareSpawnBox(res); }
/// <summary> /// Called after the view is loaded. /// </summary> protected override void AfterLoad() { if (IgnoreObject) { return; } base.AfterLoad(); // adjust size initially to text TextChanged(); if (IsToggleButton) { ToggleValueChanged(); } if (ImageComponent == null && BackgroundSpriteProperty.IsUndefined(this)) { // provide raycast target so transparent clicks are tracked if (GameObject?.GetComponent <RaycastTargetGraphic>() == null) { GameObject?.AddComponent <RaycastTargetGraphic>(); } } }
private void Start() { _commandToDirection = new Dictionary <Commands, Vector2> { { Commands.Up, Vector2.up }, { Commands.Down, Vector2.down }, { Commands.Left, Vector2.left }, { Commands.Right, Vector2.right } }; Weapon = _mainWeaponObject?.GetComponent <Weapon>(); if (_secondaryWeaponObject != null) { _secondaryWeaponObject.SetActive(false); } if (_rigidbody2D == null) { _rigidbody2D = GetComponent <Rigidbody2D>(); } _actorDisplayer = transform.GetChild(0).gameObject; _actorDisplayerController = _actorDisplayer.GetComponent <ActorDisplayerController>(); _actorDisplayerController.SetAnimationState(false); _rigidbody2D.bodyType = RigidbodyType2D.Kinematic; _isSelected = false; if (_healthPoints > 0) { _isAlive = true; } }
// Poslední (maximální) ochrana/nález komponentu(tzn. všeho co dědí z MonoB.), pro druhý stupeň => nutonost TAGU //Pozn. Možná dáme do settings. /// <summary> /// PRO DŮLEŽITÉ VĚCI!! POUZE POKUD EXISTUJE JEN TAG VE SCÉNĚ JEDNOU... Ověřuje zda je v Unity přiřazená refrence. V případě, že není, pokusí se najít. Pokud selže hodí X-| ERROR. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="toFind"> Jaký koliv objekt, dědící z objektu Component.</param> /// <param name="tag">Tag který by měl objekt ve scéně mít (defaultně Untagged).</param> /// <returns></returns> public static T IsComponentLoaded <T>(T toFind, string tag = "Untagged", string codeName = "") where T : Component { // Pokud je null if (toFind == null) { toFind = GameObject.FindObjectOfType <T>(); string ob_tag = toFind?.gameObject.tag; if (toFind == null || ob_tag == "") { Debug.LogError("Hups zase load objekt..."); } // Pokud se našel, ale není správný tag (tzn., jejich více ve stejně => jiná než find podle tagu neni // !!! JE TO EXTRÉMĚ NÁROČNÉ, proto se tomu snažíme vyhnout do poslední chvíle...) if (!ob_tag.Equals(tag)) { GameObject objectWithTag = GameObject.FindGameObjectWithTag(tag); toFind = objectWithTag?.GetComponent <T>(); // Možná v budoucnu uděláme přes arraye, namísto Find => načte všechny T ve scéně a potom, najdi s tagem v poli, ale to chece test, co je náročnější. TODO: optimalizace } } else // Jinak se vrať { return(toFind); } // Kontrola pokud proběhlo vyhledávání if (toFind == null) { Debug.LogError("Nebyl (v kódu: " + codeName + ") přiřazen objekt: " + tag); } return(toFind); }
public static bool HostileEvenIfConfused(GameObject target, GameObject caster) { var targetFaction = target?.GetComponent <Faction>(); var casterFaction = caster?.GetComponent <Faction>(); var targetAiController = GameUtilities.FindActiveAIController(target); if (targetFaction?.IsHostile(caster) == true || casterFaction?.IsHostile(target) == true) { //they're actually hostile return(true); } if (targetAiController == null) { //not AI controller. Can never be confused. return(false); } if (!IEModOptions.TargetTurnedEnemies) { //no more checks if the option is disabled. return(false); } var targetOriginal = targetAiController.GetOriginalTeam()?.GetRelationship(casterFaction?.CurrentTeam) == Faction.Relationship.Hostile; return(targetOriginal); }
private void ShootProjectile() { GameObject projectileGameObject = _objectPooler.SpawnFromPool(currentWeapon.Projectile.ToString(), _weaponTransform.position, Quaternion.identity); ProjectileMovement projectileInstance = projectileGameObject?.GetComponent <ProjectileMovement>(); projectileInstance?.SetRotation(_weaponTransform.rotation); }
public static void Create(Vector3 pos, float intensity) { GameObject explo = new GameObject(GameRes.Data.Prefabs.ExploEffect_Prefab); explo.GetComponent<ExploEffect>().Intensity = intensity; explo.Transform.Pos = pos; Scene.Current.RegisterObj(explo); }
private void SelectObjectColor(GameObject _selectedObject) { //if our last selected object is an ASL object and is not null then... if (m_SelectedObject?.GetComponent <ASL.ASLObject>() != null) { GameObject previouslySelectedObject = m_SelectedObject; //As m_SelectedObject will be updated before claim is processed, get a handle to it m_SelectedObject.GetComponent <ASL.ASLObject>().SendAndSetClaim(() => //Claim our previously selected object briefly in order to reset color { //Though called with m_Selected, use previouslySelectedObject now as mSelected may equal something else, since this code is a callback function previouslySelectedObject.GetComponent <ASL.ASLObject>().m_ReleaseFunction.Invoke(previouslySelectedObject); previouslySelectedObject.GetComponent <ASL.ASLObject>()._LocallyRemoveReleaseCallback(); }, 1000, false); //Don't reset release timer - release asap. } m_SelectedObject = _selectedObject; //Updated selected object if (m_SelectedObject?.GetComponent <ASL.ASLObject>() != null) { GameObject currentlySelected = m_SelectedObject; //Update color to let us and others know this object is selected by a user m_SelectedObject.GetComponent <ASL.ASLObject>().SendAndSetClaim(() => { currentlySelected.GetComponent <ASL.ASLObject>().SendAndSetObjectColor(Color.yellow, Color.cyan); currentlySelected.GetComponent <ASL.ASLObject>()._LocallySetReleaseFunction(OnRelease); //Call this function when we no longer own this object }, 0); //By setting timeout to 0 we are keeping this object until someone steals it from us - thus forcing the OnRelease function to only occur when stolen } }
void Start() { m_barImg = m_planetHP_bar?.GetComponent <Image>(); m_hpTxt = m_planetHp_text?.GetComponent <Text>(); m_curRatio = 0f; }
public void Attack(Player attacker) { if (Time.time - lastAttackTime > attackInterval) { lastAttackTime = Time.time; var animator = weaponModel?.GetComponent <Animator>(); if (animator) { animator.SetTrigger("Attack"); } var isHit = Physics.Raycast(weaponModel.transform.position, attacker.playerCamera.transform.forward, out RaycastHit rayHit, attackRange); if (isHit) { var monster = rayHit.collider.GetComponentInParent <Monster>(); if (monster != null) { monster.ApplyDamage(hpDamage); } } } }
internal static Vector2 CheckCollision(GameObject gameObject, Vector2 position) { foreach (GameObject other in GameObject.GameObjects) { if (other == gameObject){ continue; } Projectile projectile = gameObject.GetComponent<Projectile>(); Projectile projectileOther = other.GetComponent<Projectile>(); if ((projectile != null && projectile.Owner == other) || (projectileOther != null && projectileOther.Owner == gameObject)) { continue; } Collider otherCollider = other.GetComponent<Collider>(); if (otherCollider == null) { continue; } // if inside CollisionPoint collisionPoint = FindCollisionPoint(gameObject, other, gameObject.Position, position); if (collisionPoint != null) { position = collisionPoint.Point; gameObject.OnCollision(other, position); } } return position; }
void GenerateSandstorm() { Vector2 randomPoint = Maths.RandomPointOnRect(bounds); Vector3 point = new Vector3(randomPoint.x, randomPoint.y, 0f); float speed = Random.Range(minSpeed, maxSpeed); float lifeTime = Random.Range(minLifeTime, maxLifeTime); // Probably make direction point towards a random point around the camera Vector3 direction = point - mainCamera.transform.position; direction.z = 0f; float dirSign = Mathf.Sign(direction.magnitude); direction = direction.normalized * -dirSign; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward); currentSandstorm = GameObject.Instantiate(sandstormPrefab, point - (direction * -dirSign * buffer), rotation); Sandstorm sandstorm = currentSandstorm?.GetComponent <Sandstorm>(); sandstorm.lifeTime = lifeTime; sandstorm.moveSpeed = speed; sandstorm.moveDirection = direction; sandstorm.destroyEvent = KillSandstorm; sandstorm.initialized = true; }
public override void Interact(GameObject interactor) { interactor?.GetComponent <Inventory>()?.AddPassengers(passengers); TrainBuilder.Instance.BuildWagon(interactor.GetComponent <TrainManager>(), WagonType.LostPassenger); interactor?.GetComponentInChildren <PickingUp>().PlaySound(clip); this.gameObject.SetActive(false); }
private void Interact(bool pressed) { if (focus?.GetComponent <Interactible>() != null) { focus.GetComponent <Interactible>().Interact(pressed); } }
public new bool TestGameObject(GameObject go) { var result = false; var c = go.GetComponent(Type, true); if (c != null) { result = base.TestGameObject(go); } return result; }
private void UpdatePosition(GameObject obj, float speed) { Vector3 pos = obj.Transform.Pos; float textureWidth = obj.GetComponent<SpriteRenderer>().SharedMaterial.Res.MainTexture.Res.Size.X; pos.X -= speed; if (pos.X < -textureWidth) pos.X += textureWidth; obj.Transform.Pos = pos; }
public override void OnCollision(GameObject other, Vector2 position) { var health = other.GetComponent<Health>(); AttachedTo.MarkForDestruction(); if (health == null) return; health.CurrentHealth -= Damage; Console.WriteLine(health.CurrentHealth); //other.MarkForDestruction(); }
public BehaviourTreeNode( Game1 game, GameObject parent, BehaviourNodeType type) { this._type = type; this._state = BehaviourNodeState.Ready; this._children = new List<BehaviourTreeNode>(); this._behaviourComponent = (BehaviourComponent)parent.GetComponent(ComponentType.Behaviour); this._parent = parent; this._game = game; }
void OnTriggerEnter(GameObject collider) { var bc = collider.GetComponent<BulletControl>(); if (bc != null) { if (bc.Side == Side.Player) { Destroy(Owner); Destroy(collider); } } }
/// <summary> /// Returns true if the specified <see cref="GameObject"/> has any of the matching /// <see cref="Component"/> types, or if the filter is empty. /// </summary> /// <param name="obj"></param> /// <returns></returns> public bool Matches(GameObject obj) { if (this.typeIds.Count == 0) return true; this.UpdateTypeCache(); foreach (Type type in this.typeCache) { if (obj.GetComponent(type) != null) return true; } return false; }
public bool GetBestPath(GameObject obj, GameTime gameTime, AStarGraph graph) { Stack<AStarNode> path = new Stack<AStarNode>(); Transform2DComponent transformComponent = (Transform2DComponent)obj.GetComponent(ComponentType.Transform2D); AStarComponent aStarComponent = (AStarComponent)obj.GetComponent(ComponentType.AStar); if (transformComponent == null || aStarComponent == null) { return false; } AStarNode entityNode = graph.GetClosestNode(transformComponent.GetTranslation()); aStarComponent.CurrentNode = entityNode; AStarNode goalNode; if (aStarComponent.Follow) { GameObject entity = aStarComponent.EntityToFollow; Transform2DComponent entityTransformComponent = (Transform2DComponent)entity.GetComponent(ComponentType.Transform2D); aStarComponent.EntityToFollowPosBuffer = entityTransformComponent.GetTranslation(); goalNode = graph.GetClosestNode(aStarComponent.EntityToFollowPosBuffer); } else { goalNode = graph.GetClosestNode(aStarComponent.GoalPosition); } this.resolvePath(aStarComponent, entityNode, goalNode, graph); return true; }
void OnEnable() { if (effector == null) { GameObject effectorobj = new GameObject("effector"); effectRoot = new GameObject("ShineEffect"); effectRoot.transform.SetParent(this.transform); effectRoot.AddComponent<Image>().sprite = gameObject.GetComponent<Image>().sprite; effectRoot.GetComponent<Image>().type = gameObject.GetComponent<Image>().type; effectRoot.AddComponent<Mask>().showMaskGraphic = false; effectRoot.transform.localScale = Vector3.one; effectRoot.GetComponent<RectTransform>().anchoredPosition3D = Vector3.zero; effectRoot.GetComponent<RectTransform>().anchorMax = Vector2.one; effectRoot.GetComponent<RectTransform>().anchorMin = Vector2.zero; effectRoot.GetComponent<RectTransform>().offsetMax = Vector2.zero; effectRoot.GetComponent<RectTransform>().offsetMin = Vector2.zero; effectRoot.transform.SetAsFirstSibling(); effectorobj.AddComponent<RectTransform>(); effectorobj.transform.SetParent(effectRoot.transform); effectorRect = effectorobj.GetComponent<RectTransform>(); effectorRect.localScale = Vector3.one; effectorRect.anchoredPosition3D = Vector3.zero; effectorRect.gameObject.AddComponent<ShineEffect>(); effectorRect.anchorMax = Vector2.one; effectorRect.anchorMin = Vector2.zero; effectorRect.Rotate(0, 0, -8); effector = effectorobj.GetComponent<ShineEffect>(); effectorRect.offsetMax = Vector2.zero; effectorRect.offsetMin = Vector2.zero; OnValidate(); } }
public Transform(GameObject gameObject) : base(gameObject) { if (gameObject.GetComponent<Transform>() != null) { } this.children = new List<Transform>(); this.position = Vector2.Zero; this.rotation = 0f; this.scale = Vector2.One; this.SineOfRotation = (float)Math.Sin(rotation); this.CosineOfRotation = (float)Math.Cos(rotation); }
public void ActiveSingleTree() { var scene = new Scene(); Scene.SwitchTo(scene); var parent = new GameObject() {ActiveSingle = false, ParentScene = scene}; var child = new GameObject() {Parent = parent, ActiveSingle = false}; var grandChild = new GameObject() {Parent = child, ActiveSingle = false }; child.AddComponent<TrackActivationComponent>(); grandChild.AddComponent<TrackActivationComponent>(); parent.ActiveSingleTree = true; Assert.IsFalse(child.GetComponent<TrackActivationComponent>().WasInitialized); Assert.IsFalse(grandChild.GetComponent<TrackActivationComponent>().WasInitialized); }
// Creates a new Canvas GameObject public static Canvas CreateCanvas( string canvasName = "" ) { // Root for the UI var go = new GameObject(canvasName, typeof( Canvas ), typeof( CanvasScaler ), typeof( GraphicRaycaster ) ); if( canvasName == "" ) go.name = "Spawned Canvas"; go.layer = LayerMask.NameToLayer( "UI" ); Canvas canvas = go.GetComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; // if there is no event system add one... CreateEventSystem(); return canvas; }
public static GameObject CreateOctreeNode(uint nodeHandle, GameObject parentGameObject) { // Get node position from Cubiquity CuOctreeNode cuOctreeNode = CubiquityDLL.GetOctreeNode(nodeHandle); int xPos = cuOctreeNode.posX, yPos = cuOctreeNode.posY, zPos = cuOctreeNode.posZ; // Build a corresponding game object StringBuilder name = new StringBuilder("OctreeNode (" + xPos + ", " + yPos + ", " + zPos + ")"); GameObject newGameObject = new GameObject(name.ToString ()); newGameObject.hideFlags = HideFlags.HideInHierarchy; // Use parent properties as appropriate newGameObject.transform.parent = parentGameObject.transform; newGameObject.layer = parentGameObject.layer; // It seems that setting the parent does not cause the object to move as Unity adjusts // the child transform to compensate (this can be seen when moving objects between parents // in the hierarchy view). Reset the local transform as shown here: http://goo.gl/k5n7M7 newGameObject.transform.localRotation = Quaternion.identity; newGameObject.transform.localPosition = Vector3.zero; newGameObject.transform.localScale = Vector3.one; // Attach an OctreeNode component OctreeNode octreeNode = newGameObject.AddComponent<OctreeNode>(); octreeNode.lowerCorner = new Vector3(xPos, yPos, zPos); // Does the parent game object have an octree node attached? OctreeNode parentOctreeNode = parentGameObject.GetComponent<OctreeNode>(); if(parentOctreeNode) { // Cubiquity gives us absolute positions for the Octree nodes, but for a hierarchy of // GameObjects we need relative positions. Obtain these by subtracting parent position. newGameObject.transform.localPosition = octreeNode.lowerCorner - parentOctreeNode.lowerCorner; } else { // If not then the parent must be the Volume GameObject and the one we are creating // must be the root of the Octree. In this case we can use the position directly. newGameObject.transform.localPosition = octreeNode.lowerCorner; } return newGameObject; }
internal void SetLocalObject(NetworkInstanceId netId, GameObject obj, bool isClient, bool isServer) { if (LogFilter.logDev) Debug.Log((object) ("SetLocalObject " + (object) netId + " " + (object) obj)); if ((Object) obj == (Object) null) { this.m_LocalObjects[netId] = (NetworkIdentity) null; } else { NetworkIdentity networkIdentity = (NetworkIdentity) null; if (this.m_LocalObjects.ContainsKey(netId)) networkIdentity = this.m_LocalObjects[netId]; if ((Object) networkIdentity == (Object) null) { networkIdentity = obj.GetComponent<NetworkIdentity>(); this.m_LocalObjects[netId] = networkIdentity; } networkIdentity.UpdateClientServer(isClient, isServer); } }
internal static void RegisterPrefab(GameObject prefab) { NetworkIdentity component = prefab.GetComponent<NetworkIdentity>(); if (component) { if (LogFilter.logDebug) { Debug.Log(string.Concat(new object[] { "Registering prefab '", prefab.get_name(), "' as asset:", component.assetId })); } NetworkScene.s_GUIDToPrefab[component.assetId] = prefab; } else if (LogFilter.logError) { Debug.LogError("Could not register '" + prefab.get_name() + "' since it contains no NetworkIdentity component"); } }
private void AddGenericMenuButton(Transform _parent, int _index, int _numButtons, float _buttonVertBlockPercentage) { // Button Game Object GameObject genericMenuButton = new GameObject("Generic Menu Button"); genericMenuButton.transform.SetParent(_parent); Image genericMenuButtonImage = genericMenuButton.AddComponent<Image>(); genericMenuButtonImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath); genericMenuButtonImage.type = Image.Type.Sliced; Button genericMenuButtonButton = genericMenuButton.AddComponent<Button>(); ColorBlock colors = (genericMenuButtonButton as Selectable).colors; colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f); colors.pressedColor = new Color(0.698f, 0.698f, 0.698f); colors.disabledColor = new Color(0.521f, 0.521f, 0.521f); genericMenuButtonButton.onClick = thisGO.GetComponent<GenericMenu>().mArrButtonEvents[_index]; RectTransform genericMenuButtonRT = genericMenuButton.GetComponent<RectTransform>(); Vector2 anchorMin = Vector2.zero; Vector2 anchorMax = Vector2.one; // Settle anchor X minmax. anchorMin.x = (1.0f - mSP_ButtonHorzPercent.floatValue) / 2.0f; anchorMax.x = 1.0f - anchorMin.x; // Settle anchor y minmax. anchorMax.y = 1.0f - mSP_MenuPaddingTop.floatValue - mSP_ButtonVertMargin.floatValue - (_buttonVertBlockPercentage * _index); anchorMin.y = anchorMax.y - _buttonVertBlockPercentage + (mSP_ButtonVertMargin.floatValue * 2); genericMenuButtonRT.anchorMin = anchorMin; genericMenuButtonRT.anchorMax = anchorMax; genericMenuButtonRT.sizeDelta = Vector2.zero; genericMenuButtonRT.anchoredPosition = Vector2.zero; // Button Text Child Object GameObject childText = new GameObject("Text"); GameObjectUtility.SetParentAndAlign(childText, genericMenuButton); Text text = childText.AddComponent<Text>(); text.text = thisGO.GetComponent<GenericMenu>().mArrStrButtonNames[_index]; text.color = Color.black; text.alignment = TextAnchor.MiddleCenter; text.rectTransform.anchorMin = Vector2.zero; text.rectTransform.anchorMax = Vector2.one; text.rectTransform.sizeDelta = Vector2.zero; text.rectTransform.anchoredPosition = Vector2.zero; }
private void ConstructCanvasFromScratch() { // Destroy previous canvas. DestroyCanvas(); // Child Canvas Object GameObject genericMenuCanvas = new GameObject("Generic Menu Canvas"); genericMenuCanvas.transform.SetParent(thisGO.transform); genericMenuCanvas.AddComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay; genericMenuCanvas.AddComponent<CanvasScaler>(); genericMenuCanvas.AddComponent<GraphicRaycaster>(); // Panel GameObject genericMenuPanel = new GameObject("Generic Menu Panel"); genericMenuPanel.transform.SetParent(genericMenuCanvas.transform); Image genericMenuPanelImage = genericMenuPanel.AddComponent<Image>(); genericMenuPanelImage.sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpriteResourcePath); genericMenuPanelImage.type = Image.Type.Sliced; RectTransform genericMenuPanelRT = genericMenuPanel.GetComponent<RectTransform>(); genericMenuPanelRT.anchoredPosition = Vector2.zero; genericMenuPanelRT.sizeDelta = mSP_MenuSize.vector2Value; // Buttons int numButtons = mSP_ButtonNames.arraySize; float buttonVertBlockPercentage = (1.0f - mSP_MenuPaddingTop.floatValue - mSP_MenuPaddingBottom.floatValue) / numButtons; for (int i = 0; i < numButtons; i++) { AddGenericMenuButton(genericMenuPanel.transform, i, numButtons, buttonVertBlockPercentage); } }
// Use this for initialization void Start() { Debug.Log ("Llamado al metodo START de MenuOfStepsPhase2 - Instancia:" + this.gameObject.GetInstanceID() + " name:" + this.gameObject.name); //inicializando variable que controla si todos los items estan en los slots: items_ubicados_correctamente = false; //inicializando la variable que indica si se ha pedido organizar automaticamente los pasos //por el appmanager: //steps_organized_from_manager = false; //desactivando el tick de orden correcto hasta que se obtenga el orden correcto: if (tickCorrectOrder != null) tickCorrectOrder.enabled = false; //cargando la imagen del tick y del boton warning: img_tick = Resources.Load<Sprite> ("Sprites/buttons/tick"); img_warning = Resources.Load<Sprite> ("Sprites/buttons/warning_order"); //obteniendo el componente del encabezado de la imagen: imagen_header = GameObject.Find ("header_image_menuphase2_eval"); if (imagen_header != null) { Debug.Log ("La imagen del HEADER es: " + image_header_phase1); sprite_image_header_phase1 = Resources.Load<Sprite> (image_header_phase1); imagen_header.GetComponent<Image>().sprite = sprite_image_header_phase1; } //obteniendo el componente text que se llama titulo en el prefab: //titulo_object = GameObject.Find ("title_menu_steps_phase2_text_eval"); if (titulo_object != null) { Debug.LogError ("Se va a cambiar el TITULO de la interfaz es: " + titulo); titulo_object.GetComponent<Text> ().text = titulo; } else { Debug.LogError("Error: No se encuentra el objeto TITULO para la interfaz en MenuOfStepsPhaseTwoManagerEval"); } //colocando el texto de la introduccion: //introduction_object = GameObject.Find ("introduction_steps_of_phase1_interface"); if (introduction_object != null) { Debug.LogError ("Se va a cambiar el texto de la INTRODUCCION"); introduction_asset = Resources.Load (introduction_text_path) as TextAsset; introduction_object.GetComponent<Text> ().text = introduction_asset.text; } else { Debug.LogError("Error: No se encuentra el objeto INTRODUCCION para la interfaz en MenuOfStepsPhaseTwoManagerEval"); } //accion regresar en el boton if(regresar != null){ Debug.LogError("Se agrega la accion al boton REGRESAR"); regresar.onClick.AddListener(()=>{ActionButton_goBackToMenuPhases();}); } //accion ir al Step1 del Phase //colocando las imagenes de las fases despues del encabezado (guia del proceso completo para los estudiantes) //image_phase1_object = GameObject.Find ("image_phase1"); if (image_phase1_object != null) { image_phase1_sprite = Resources.Load<Sprite> (image_phase1_path); image_phase1_object.GetComponent<Image> ().sprite = image_phase1_sprite; } else { Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval"); } //image_phase2_object = GameObject.Find ("image_phase2"); if (image_phase2_object != null) { image_phase2_sprite = Resources.Load<Sprite>(image_phase2_path); image_phase2_object.GetComponent<Image>().sprite = image_phase2_sprite; }else { Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval"); } //image_phase3_object = GameObject.Find ("image_phase3"); if (image_phase3_object != null) { image_phase3_sprite = Resources.Load<Sprite>(image_phase3_path); image_phase3_object.GetComponent<Image>().sprite = image_phase3_sprite; }else { Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval"); } //image_phase4_object = GameObject.Find ("image_phase4"); if (image_phase4_object != null) { image_phase4_sprite = Resources.Load<Sprite>(image_phase4_path); image_phase4_object.GetComponent<Image>().sprite = image_phase4_sprite; }else { Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval"); } //image_phase5_object = GameObject.Find ("image_phase5"); if (image_phase5_object != null) { image_phase5_sprite = Resources.Load<Sprite>(image_phase5_path); image_phase5_object.GetComponent<Image>().sprite = image_phase5_sprite; }else { Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval"); } //image_phase6_object = GameObject.Find ("image_phase6"); if (image_phase6_object != null) { image_phase6_sprite = Resources.Load<Sprite>(image_phase6_path); image_phase6_object.GetComponent<Image>().sprite = image_phase6_sprite; }else { Debug.LogError("No se ha podido obtener el OBJETO IMAGEN DE FASE EN ENCABEZADO en MenuOfStepsPhaseTwoManagerEval"); } if (btn_one_to_order != null) { image_button_sprite_uno = Resources.Load<Sprite> (img_one_to_order); btn_one_to_order.GetComponent<Image>().sprite = image_button_sprite_uno; ////Agregando la accion para ir al step1 - phase 1 (buscar capo del carro): btn_one_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnOne();}); drag_controller = btn_one_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_one; } if (btn_two_to_order != null) { image_button_sprite_dos = Resources.Load<Sprite> (img_two_to_order); btn_two_to_order.GetComponent<Image>().sprite = image_button_sprite_dos; //Agregando la accion para ir al conjunto de actividades (2. limpieza): btn_two_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnTwo();}); drag_controller = btn_two_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_two; } if (btn_three_to_order != null) { image_button_sprite_tres = Resources.Load<Sprite> (img_three_to_order); btn_three_to_order.GetComponent<Image>().sprite = image_button_sprite_tres; //Agregando la accion para ir al conjunto de actividades (3. secado): btn_three_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnThree();}); drag_controller = btn_three_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_three; } if (btn_four_to_order != null) { image_button_sprite_cuatro = Resources.Load<Sprite> (img_four_to_order); btn_four_to_order.GetComponent<Image>().sprite = image_button_sprite_cuatro; //Agregando la accion para ir al conjunto de actividades (4. localizar irregularidades): btn_four_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnFour();}); drag_controller = btn_four_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_four; } if (btn_five_to_order != null) { image_button_sprite_cinco = Resources.Load<Sprite> (img_five_to_order); btn_five_to_order.GetComponent<Image>().sprite = image_button_sprite_cinco; //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades): btn_five_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnFive();}); drag_controller = btn_five_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_five; } if (btn_six_to_order != null) { image_button_sprite_seis = Resources.Load<Sprite> (img_six_to_order); btn_six_to_order.GetComponent<Image>().sprite = image_button_sprite_seis; //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades): btn_six_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnSix();}); drag_controller = btn_six_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_six; } if (btn_seven_to_order != null) { image_button_sprite_siete = Resources.Load<Sprite> (img_seven_to_order); btn_seven_to_order.GetComponent<Image>().sprite = image_button_sprite_siete; //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades): btn_seven_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnSeven();}); drag_controller = btn_seven_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_seven; } if (btn_eight_to_order != null) { image_button_sprite_ocho = Resources.Load<Sprite> (img_eight_to_order); btn_eight_to_order.GetComponent<Image>().sprite = image_button_sprite_ocho; //Agregando la accion para ir al conjunto de actividades (5. corregir irregularidades): btn_eight_to_order.onClick.AddListener(()=>{ActionButton_goToActionBtnEight();}); drag_controller = btn_eight_to_order.GetComponent<DragBehaviourMenuOfSteps>(); if(drag_controller != null) drag_controller.phase_number = step_number_btn_eight; } //colocando los textos en los botones: if(text_btn_one_to_order != null){ text_btn_one_to_order.text = this.string_btn_one_text; } if(text_btn_two_to_order != null){ text_btn_two_to_order.text = this.string_btn_two_text; } if(text_btn_three_to_order != null){ text_btn_three_to_order.text = this.string_btn_three_text; } if(text_btn_four_to_order != null){ text_btn_four_to_order.text = this.string_btn_four_text; } if(text_btn_five_to_order != null){ text_btn_five_to_order.text = this.string_btn_five_text; } if(text_btn_six_to_order != null){ text_btn_six_to_order.text = this.string_btn_six_text; } if(text_btn_seven_to_order != null){ text_btn_seven_to_order.text = this.string_btn_seven_text; } if(text_btn_eight_to_order != null){ text_btn_eight_to_order.text = this.string_btn_eight_text; } //llamado al metodo hasChanged para verificar si hay algun cambio los slots de pasos: HasChanged (); }
internal static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) { NetworkIdentity component = prefab.GetComponent<NetworkIdentity>(); if ((Object) component == (Object) null) { if (!LogFilter.logError) return; Debug.LogError((object) ("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component")); } else if (spawnHandler == null || unspawnHandler == null) { if (!LogFilter.logError) return; Debug.LogError((object) ("RegisterPrefab custom spawn function null for " + (object) component.assetId)); } else if (!component.assetId.IsValid()) { if (!LogFilter.logError) return; Debug.LogError((object) ("RegisterPrefab game object " + prefab.name + " has no prefab. Use RegisterSpawnHandler() instead?")); } else { if (LogFilter.logDebug) Debug.Log((object) ("Registering custom prefab '" + prefab.name + "' as asset:" + (object) component.assetId + " " + spawnHandler.Method.Name + "/" + unspawnHandler.Method.Name)); NetworkScene.s_SpawnHandlers[component.assetId] = spawnHandler; NetworkScene.s_UnspawnHandlers[component.assetId] = unspawnHandler; } }
internal static void UnregisterPrefab(GameObject prefab) { NetworkIdentity component = prefab.GetComponent<NetworkIdentity>(); if ((Object) component == (Object) null) { if (!LogFilter.logError) return; Debug.LogError((object) ("Could not unregister '" + prefab.name + "' since it contains no NetworkIdentity component")); } else { NetworkScene.s_SpawnHandlers.Remove(component.assetId); NetworkScene.s_UnspawnHandlers.Remove(component.assetId); } }
internal static void RegisterPrefab(GameObject prefab) { NetworkIdentity component = prefab.GetComponent<NetworkIdentity>(); if ((bool) ((Object) component)) { if (LogFilter.logDebug) Debug.Log((object) ("Registering prefab '" + prefab.name + "' as asset:" + (object) component.assetId)); NetworkScene.s_GuidToPrefab[component.assetId] = prefab; if (prefab.GetComponentsInChildren<NetworkIdentity>().Length <= 1 || !LogFilter.logWarn) return; Debug.LogWarning((object) ("The prefab '" + prefab.name + "' has multiple NetworkIdentity components. There can only be one NetworkIdentity on a prefab, and it must be on the root object.")); } else { if (!LogFilter.logError) return; Debug.LogError((object) ("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component")); } }
internal static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId) { NetworkIdentity component = prefab.GetComponent<NetworkIdentity>(); if ((bool) ((Object) component)) { component.SetDynamicAssetId(newAssetId); if (LogFilter.logDebug) Debug.Log((object) ("Registering prefab '" + prefab.name + "' as asset:" + (object) component.assetId)); NetworkScene.s_GuidToPrefab[component.assetId] = prefab; } else { if (!LogFilter.logError) return; Debug.LogError((object) ("Could not register '" + prefab.name + "' since it contains no NetworkIdentity component")); } }
public static void syncNode(ref uint availableSyncOperations, GameObject nodeGameObject, uint nodeHandle, GameObject voxelTerrainGameObject) { OctreeNode octreeNode = nodeGameObject.GetComponent<OctreeNode>(); CuOctreeNode cuOctreeNode = CubiquityDLL.GetOctreeNode(nodeHandle); //////////////////////////////////////////////////////////////////////////////// // Has anything in this node or its children changed? If so, we may need to syncronise the node's properties, mesh and // structure. Each of these can be tested against a timestamp. We may also need to do this recursively on child nodes. //////////////////////////////////////////////////////////////////////////////// if (cuOctreeNode.nodeOrChildrenLastChanged > octreeNode.nodeAndChildrenLastSynced) { bool resyncedProperties = false; // See comments where this is tested - it's a bit of a hack //////////////////////////////////////////////////////////////////////////////// // 1st test - Have the properties of the node changed? //////////////////////////////////////////////////////////////////////////////// if (cuOctreeNode.propertiesLastChanged > octreeNode.propertiesLastSynced) { octreeNode.renderThisNode = cuOctreeNode.renderThisNode != 0; octreeNode.height = cuOctreeNode.height; octreeNode.propertiesLastSynced = CubiquityDLL.GetCurrentTime(); resyncedProperties = true; } //////////////////////////////////////////////////////////////////////////////// // 2nd test - Has the mesh changed and do we have time to syncronise it? //////////////////////////////////////////////////////////////////////////////// if ((cuOctreeNode.meshLastChanged > octreeNode.meshLastSynced) && (availableSyncOperations > 0)) { if (cuOctreeNode.hasMesh == 1) { // Set up the rendering mesh VolumeRenderer volumeRenderer = voxelTerrainGameObject.GetComponent<VolumeRenderer>(); if (volumeRenderer != null) { MeshFilter meshFilter = nodeGameObject.GetOrAddComponent<MeshFilter>() as MeshFilter; if(meshFilter.sharedMesh == null) { meshFilter.sharedMesh = new Mesh(); } MeshRenderer meshRenderer = nodeGameObject.GetOrAddComponent<MeshRenderer>() as MeshRenderer; if (voxelTerrainGameObject.GetComponent<Volume>().GetType() == typeof(TerrainVolume)) { MeshConversion.BuildMeshFromNodeHandleForTerrainVolume(meshFilter.sharedMesh, nodeHandle, false); } else if (voxelTerrainGameObject.GetComponent<Volume>().GetType() == typeof(ColoredCubesVolume)) { MeshConversion.BuildMeshFromNodeHandleForColoredCubesVolume(meshFilter.sharedMesh, nodeHandle, false); } meshRenderer.enabled = volumeRenderer.enabled && octreeNode.renderThisNode; // For syncing materials, shadow properties, etc. syncNodeWithVolumeRenderer(nodeGameObject, volumeRenderer, false); } // Set up the collision mesh VolumeCollider volumeCollider = voxelTerrainGameObject.GetComponent<VolumeCollider>(); if (volumeCollider != null) { bool useCollider = volumeCollider.useInEditMode || Application.isPlaying; if (useCollider) { // I'm not quite comfortable with this. For some reason we have to create this new mesh, fill it, // and set it as the collider's shared mesh, whereas I would rather just pass the collider's sharedMesh // straight to the functon that fills it. For some reason that doesn't work properly, and we see // issues with objects falling through terrain or not updating when part of the terrain is deleted. // It's to be investigated further... perhaps we could try deleting and recreating the MeshCollider? // Still, the approach below seems to work properly. Mesh collisionMesh = new Mesh(); if (voxelTerrainGameObject.GetComponent<Volume>().GetType() == typeof(TerrainVolume)) { MeshConversion.BuildMeshFromNodeHandleForTerrainVolume(collisionMesh, nodeHandle, true); } else if (voxelTerrainGameObject.GetComponent<Volume>().GetType() == typeof(ColoredCubesVolume)) { MeshConversion.BuildMeshFromNodeHandleForColoredCubesVolume(collisionMesh, nodeHandle, true); } MeshCollider meshCollider = nodeGameObject.GetOrAddComponent<MeshCollider>() as MeshCollider; meshCollider.sharedMesh = collisionMesh; } } } // If there is no mesh in Cubiquity then we make sure there isn't one in Unity. else { MeshCollider meshCollider = nodeGameObject.GetComponent<MeshCollider>() as MeshCollider; if (meshCollider) { Utility.DestroyOrDestroyImmediate(meshCollider); } MeshRenderer meshRenderer = nodeGameObject.GetComponent<MeshRenderer>() as MeshRenderer; if (meshRenderer) { Utility.DestroyOrDestroyImmediate(meshRenderer); } MeshFilter meshFilter = nodeGameObject.GetComponent<MeshFilter>() as MeshFilter; if (meshFilter) { Utility.DestroyOrDestroyImmediate(meshFilter); } } octreeNode.meshLastSynced = CubiquityDLL.GetCurrentTime(); availableSyncOperations--; } // We want to syncronize the properties before the mesh, so that the enabled flag can be set correctly when the mesh // is created. But we also want to syncronize properties after the mesh, so we can apply the correct enabled flag to // existing meshes when the node's 'renderThisNode' flag has changed. Therefore we set the 'resyncedProperties' flag // previously to let ourseves know that we should come back an finish the propertiy syncing here. It's a bit of a hack. if (resyncedProperties) { VolumeRenderer volumeRenderer = voxelTerrainGameObject.GetComponent<VolumeRenderer>(); if(volumeRenderer != null) { syncNodeWithVolumeRenderer(nodeGameObject, volumeRenderer, false); } VolumeCollider volumeCollider = voxelTerrainGameObject.GetComponent<VolumeCollider>(); if (volumeCollider != null) { syncNodeWithVolumeCollider(nodeGameObject, volumeCollider, false); } } uint[, ,] childHandleArray = new uint[2, 2, 2]; childHandleArray[0, 0, 0] = cuOctreeNode.childHandle000; childHandleArray[0, 0, 1] = cuOctreeNode.childHandle001; childHandleArray[0, 1, 0] = cuOctreeNode.childHandle010; childHandleArray[0, 1, 1] = cuOctreeNode.childHandle011; childHandleArray[1, 0, 0] = cuOctreeNode.childHandle100; childHandleArray[1, 0, 1] = cuOctreeNode.childHandle101; childHandleArray[1, 1, 0] = cuOctreeNode.childHandle110; childHandleArray[1, 1, 1] = cuOctreeNode.childHandle111; //////////////////////////////////////////////////////////////////////////////// // 3rd test - Has the structure of the octree node changed (gained or lost children)? //////////////////////////////////////////////////////////////////////////////// if (cuOctreeNode.structureLastChanged > octreeNode.structureLastSynced) { //Now syncronise any children for (uint z = 0; z < 2; z++) { for (uint y = 0; y < 2; y++) { for (uint x = 0; x < 2; x++) { if (childHandleArray[x, y, z] != 0xFFFFFFFF) { uint childNodeHandle = childHandleArray[x, y, z]; if (octreeNode.GetChild(x, y, z) == null) { octreeNode.SetChild(x, y, z, OctreeNode.CreateOctreeNode(childNodeHandle, nodeGameObject)); } } else { if (octreeNode.GetChild(x, y, z)) { Utility.DestroyOrDestroyImmediate(octreeNode.GetChild(x, y, z)); octreeNode.SetChild(x, y, z, null); } } } } } octreeNode.structureLastSynced = CubiquityDLL.GetCurrentTime(); } //////////////////////////////////////////////////////////////////////////////// // The last step of syncronization is to apply it recursively to our children. //////////////////////////////////////////////////////////////////////////////// for (uint z = 0; z < 2; z++) { for (uint y = 0; y < 2; y++) { for (uint x = 0; x < 2; x++) { if (octreeNode.GetChild(x, y, z) != null && availableSyncOperations > 0) { OctreeNode.syncNode(ref availableSyncOperations, octreeNode.GetChild(x, y, z), childHandleArray[x, y, z], voxelTerrainGameObject); } } } } // We've reached the end of our syncronization process. If there are still sync operations available then // we did less work then we could have, which implies we finished. Therefore mark the whole tree as synced. if (availableSyncOperations > 0) { octreeNode.nodeAndChildrenLastSynced = CubiquityDLL.GetCurrentTime(); } } }