/// <summary> /// Decrease the alpha value of the muzzle flash to give it a fading effect. As soon as the alpha value reaches zero place the muzzle flash back in /// the object pool. If a light exists decrease the intensity of the light as well. /// </summary> private void Update() { if (m_Color.a > 0) { m_Color.a = Mathf.Max(m_Color.a - (m_FadeSpeed * Time.deltaTime * m_TimeScale), 0); if (m_Material != null) { m_Material.SetColor(m_TintColorPropertyID, m_Color); } // Keep the light intensity synchronized with the alpha channel's value. if (m_Light != null) { m_Light.intensity = m_StartLightIntensity * (m_Color.a / m_StartAlpha); } } else { if (m_Pooled) { ObjectPoolBase.Destroy(m_GameObject); } else { m_GameObject.SetActive(false); } } }
/// <summary> /// Fade out the decals in the decals to fade list. /// </summary> private void Update() { for (int i = m_DecalsToFade.Count - 1; i >= 0; --i) { if (m_DecalsToFade[i] == null) { m_DecalsToFade.RemoveAt(i); continue; } var color = m_DecalsToFade[i].material.color; color.a = Mathf.Lerp(color.a, 0, Time.deltaTime * m_RemoveFadeoutSpeed); // The decal can be removed from the list when it is completely faded out. if (color.a == 0) { ObjectPoolBase.Destroy(m_DecalsToFade[i].gameObject); m_DecalsToFade.RemoveAt(i); } else { m_DecalsToFade[i].material.color = color; } } // The component can be disabled when there are no decals within the list. if (m_DecalsToFade.Count == 0) { enabled = false; } }
/// <summary> /// Perform the impact action. /// </summary> /// <param name="castID">The ID of the cast.</param> /// <param name="source">The object that caused the cast.</param> /// <param name="target">The object that was hit by the cast.</param> /// <param name="hit">The raycast that caused the impact.</param> protected override void ImpactInternal(uint castID, GameObject source, GameObject target, RaycastHit hit) { if (m_ParticlePrefab == null) { Debug.LogError("Error: A Particle Prefab must be specified.", m_MagicItem); return; } var rotation = Quaternion.LookRotation(hit.normal) * Quaternion.Euler(m_RotationOffset); var position = MathUtility.TransformPoint(hit.point, rotation, m_PositionOffset); if (m_CastIDParticleMap.TryGetValue(castID, out var existingParticleSystem)) { existingParticleSystem.transform.SetPositionAndRotation(position, rotation); return; } var obj = ObjectPoolBase.Instantiate(m_ParticlePrefab, position, rotation, m_ParentToImpactedObject ? target.transform : null); var particleSystem = obj.GetCachedComponent <ParticleSystem>(); if (particleSystem == null) { Debug.LogError($"Error: A Particle System must be specified on the particle {m_ParticlePrefab}.", m_MagicItem); return; } particleSystem.Clear(true); m_CastIDParticleMap.Add(castID, particleSystem); }
/// <summary> /// Does the actual fire. /// </summary> public void Fire() { m_LastFireTime = Time.time; // Spawn a projectile which will move in the direction that the turret is facing var projectile = ObjectPoolBase.Instantiate(m_Projectile, m_FireLocation.position, m_Transform.rotation).GetCachedComponent <Projectile>(); projectile.Initialize(m_FireLocation.forward * m_VelocityMagnitude, Vector3.zero, null, m_DamageAmount, m_ImpactForce, m_ImpactForceFrames, m_ImpactLayers, string.Empty, 0, m_SurfaceImpact, m_GameObject); #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (m_NetworkInfo != null) { NetworkObjectPool.NetworkSpawn(m_Projectile, projectile.gameObject, true); } #endif // Spawn a muzzle flash. if (m_MuzzleFlash) { var muzzleFlash = ObjectPoolBase.Instantiate(m_MuzzleFlash, m_MuzzleFlashLocation.position, m_MuzzleFlashLocation.rotation, m_Transform).GetCachedComponent <MuzzleFlash>(); muzzleFlash.Show(null, 0, true, null); } // Play a firing sound. if (m_FireAudioClip != null) { m_AudioSource.clip = m_FireAudioClip; m_AudioSource.Play(); } }
/// <summary> /// Instantiate the object. /// </summary> /// <param name="position">The position to instantiate the object at.</param> /// <param name="normal">The normal of the instantiated object.</param> /// <param name="gravityDirection">The normalized direction of the character's gravity.</param> /// <returns>The instantiated object (can be null). </returns> public GameObject Instantiate(Vector3 position, Vector3 normal, Vector3 gravityDirection) { if (m_Object == null) { return(null); } // There is a random chance that the object cannot be spawned. if (UnityEngine.Random.value < m_Probability) { var rotation = Quaternion.LookRotation(normal); // A random spin can be applied so the rotation isn't the same every hit. if (m_RandomSpin) { rotation *= Quaternion.AngleAxis(UnityEngine.Random.Range(0, 360), normal); } var instantiatedObject = ObjectPoolBase.Instantiate(m_Object, position, rotation); // If the DirectionalConstantForce component exists then the gravity direction should be set so the object will move in the correct direction. var directionalConstantForce = instantiatedObject.GetCachedComponent <Traits.DirectionalConstantForce>(); if (directionalConstantForce != null) { directionalConstantForce.Direction = gravityDirection; } return(instantiatedObject); } return(null); }
/// <summary> /// Initialize the default values. /// </summary> protected override void Awake() { base.Awake(); m_TrajectoryObject = GetComponent <TrajectoryObject>(); m_CharacterLocomotion = m_Character.GetCachedComponent <UltimateCharacterLocomotion>(); m_CharacterTransform = m_CharacterLocomotion.transform; #if ULTIMATE_CHARACTER_CONTROLLER_VR m_VRThrowableItem = GetComponent <IVRThrowableItem>(); #endif if (m_ThrownObject != null && m_TrajectoryObject != null) { // The object has to be instantiated for GetComponent to work. var instantiatedThrownObject = ObjectPoolBase.Instantiate(m_ThrownObject); var trajectoryCollider = instantiatedThrownObject.GetComponent <Collider>(); if (trajectoryCollider != null) { // Only sphere and capsules are supported. if (trajectoryCollider is SphereCollider) { var trajectorySphereCollider = trajectoryCollider as SphereCollider; var sphereCollider = m_GameObject.AddComponent <SphereCollider>(); sphereCollider.center = trajectorySphereCollider.center; sphereCollider.radius = trajectorySphereCollider.radius; sphereCollider.enabled = false; } else if (trajectoryCollider is CapsuleCollider) { var trajectoryCapsuleCollider = trajectoryCollider as CapsuleCollider; var capsuleCollider = m_GameObject.AddComponent <CapsuleCollider>(); capsuleCollider.center = trajectoryCapsuleCollider.center; capsuleCollider.radius = trajectoryCapsuleCollider.radius; capsuleCollider.height = trajectoryCapsuleCollider.height; capsuleCollider.direction = trajectoryCapsuleCollider.direction; capsuleCollider.enabled = false; } else { Debug.LogError($"Error: The collider of type {trajectoryCollider.GetType()} is not supported on the trajectory object " + m_ThrownObject.name); } m_GameObject.layer = LayerManager.SubCharacter; } ObjectPoolBase.Destroy(instantiatedThrownObject); } m_ThrowableItemPerpectiveProperties = m_ActivePerspectiveProperties as IThrowableItemPerspectiveProperties; if (m_ShowTrajectoryOnAim && m_TrajectoryObject == null) { Debug.LogError($"Error: A TrajectoryObject must be added to the {m_GameObject.name} GameObject in order for the trajectory to be shown."); } if (m_ThrownObject == null) { Debug.LogError($"Error: A ThrownObject must be assigned to the {m_GameObject.name} GameObject."); } EventHandler.RegisterEvent <bool, bool>(m_Character, "OnAimAbilityStart", OnAim); EventHandler.RegisterEvent(m_Character, "OnAnimatorReequipThrowableItem", ReequipThrowableItem); }
/// <summary> /// Reduces the health by the damage amount. /// </summary> private void ReduceHealth() { m_Health.Damage(m_DamageAmount.RandomValue); if (m_Health.IsAlive()) { // Keep reducing the object's health until is is no longer alive. SchedulerBase.Schedule(m_HealthReductionInterval.RandomValue, ReduceHealth); } else { // After the object is no longer alive spawn some wood shreds. These shreds should be cleaned up after a random // amount of time. var crateTransform = transform; m_SpawnedCrate = ObjectPoolBase.Instantiate(m_DestroyedCrate, crateTransform.position, crateTransform.rotation); var maxDestroyTime = 0f; for (int i = 0; i < m_SpawnedCrate.transform.childCount; ++i) { var destroyTime = m_WoodShreadRemovalTime.RandomValue; if (destroyTime > maxDestroyTime) { maxDestroyTime = destroyTime; } Destroy(m_SpawnedCrate.transform.GetChild(i).gameObject, destroyTime); } m_StopEvent = SchedulerBase.Schedule(maxDestroyTime, StopParticles); } }
public static void DomainReset() { EventHandler.DomainReset(); GameObjectExtensions.DomainReset(); ObjectPoolBase.DomainReset(); SchedulerBase.DomainReset(); }
/// <summary> /// 在池库中找需要的游戏物体,没有就生成新的池添加进字典 /// </summary> /// <param 预制体="obj"></param> /// <returns></returns> internal GameObject InstantiateMyGameObject(GameObject obj) { if (!objectPoolDictionary.ContainsKey(obj.name)) { ObjectPoolBase newPool = new ObjectPoolBase(obj); objectPoolDictionary.Add(newPool.Name, newPool); } return(objectPoolDictionary[obj.name].InstantiateGameObject()); }
/// <summary> /// Starts the item use. /// </summary> /// <param name="itemAbility">The item ability that is using the item.</param> public override void StartItemUse(ItemAbility itemAbility) { base.StartItemUse(itemAbility); // An Animator Audio State Set may prevent the item from being used. if (!IsItemInUse()) { return; } if (!m_ThrowOnStopUse) { StartThrow(); } // Instantiate the object that will actually be thrown. var location = m_ThrowableItemPerpectiveProperties.ThrowLocation; m_InstantiatedThrownObject = ObjectPoolBase.Instantiate(m_ThrownObject, location.position, location.rotation, m_ObjectTransform.parent); m_InstantiatedThrownObject.transform.localScale = location.localScale; m_InstantiatedThrownObject.transform.SetLayerRecursively(m_StartLayer); m_InstantiatedTrajectoryObject = m_InstantiatedThrownObject.GetCachedComponent <TrajectoryObject>(); if (m_InstantiatedTrajectoryObject == null) { Debug.LogError($"Error: {m_TrajectoryObject.name} must contain the TrajectoryObject component."); return; } if (m_InstantiatedTrajectoryObject is Destructible) { (m_InstantiatedTrajectoryObject as Destructible).InitializeDestructibleProperties(m_DamageProcessor, m_DamageAmount, m_ImpactForce, m_ImpactForceFrames, m_ImpactLayers, m_ImpactStateName, m_ImpactStateDisableTimer, m_SurfaceImpact); } // The trajectory object will be enabled when the object is thrown. m_InstantiatedTrajectoryObject.enabled = false; // Hide the object that isn't thrown. EnableObjectMeshRenderers(false); // The instantiated object may not immediately be visible. if (m_DisableVisibleObject) { m_InstantiatedThrownObject.SetActive(false); m_ActivateVisibleObject = false; m_Item.SetVisibleObjectActive(false, true); if (m_ActivateThrowableObjectEvent.WaitForAnimationEvent) { EventHandler.RegisterEvent(m_Character, "OnAnimatorActivateThrowableObject", ActivateThrowableObject); } else { SchedulerBase.ScheduleFixed(m_ActivateThrowableObjectEvent.Duration, ActivateThrowableObject); } } }
/// <summary> /// Move and rotate the object according to a parabolic trajectory. /// </summary> protected override void FixedUpdate() { base.FixedUpdate(); if (Time.time > m_RemoveTime) // The shell should be removed. { m_Transform.localScale = Vector3.Lerp(m_Transform.localScale, Vector3.zero, TimeUtility.FramerateDeltaTime * 0.2f); if (Time.time > m_RemoveTime + 0.5f) { ObjectPoolBase.Destroy(m_GameObject); } } }
public override void Dispose() { base.Dispose(); ObjectPoolBase tmpObjPool = GetPoolByType(Parent.UnitType); if (null != tmpObjPool) { tmpObjPool.Unspawn(mHudInfo); } mHudInfo = null; }
public bool DestroyPool <T>(string key) where T : Component, new() { ObjectPoolBase pool = null; if (poolDictionary.TryGetValue(key, out pool) == false) { return(false); } ObjectPool <T> realPool = pool as ObjectPool <T>; realPool.DestoryAll(); return(true); }
/// <summary> /// Destroys the object. /// </summary> /// <param name="hitPosition">The position of the destruction.</param> /// <param name="hitNormal">The normal direction of the destruction.</param> public void Destruct(Vector3 hitPosition, Vector3 hitNormal) { for (int i = 0; i < m_SpawnedObjectsOnDestruction.Length; ++i) { if (m_SpawnedObjectsOnDestruction[i] == null) { continue; } var spawnedObject = m_SpawnedObjectsOnDestruction[i].Instantiate(hitPosition, hitNormal, m_NormalizedGravity); if (spawnedObject == null) { continue; } var explosion = spawnedObject.GetCachedComponent <Explosion>(); if (explosion != null) { explosion.Explode(m_DamageAmount, m_ImpactForce, m_ImpactForceFrames, m_Originator); } } // The component and collider no longer need to be enabled after the object has been destroyed. if (m_Collider != null) { m_Collider.enabled = false; } if (m_ParticleSystem != null) { m_ParticleSystem.Stop(); } m_Destroyed = true; m_DestroyEvent = null; enabled = false; // The destructible should be destroyed. #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (NetworkObjectPool.IsNetworkActive()) { // The object may have already been destroyed over the network. if (!m_GameObject.activeSelf) { return; } NetworkObjectPool.Destroy(m_GameObject); return; } #endif ObjectPoolBase.Destroy(m_GameObject); }
/// <summary> /// Performs the cast. /// </summary> /// <param name="origin">The location that the cast should spawn from.</param> /// <param name="direction">The direction of the cast.</param> /// <param name="targetPosition">The target position of the cast.</param> public override void Cast(Transform origin, Vector3 direction, Vector3 targetPosition) { #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER // The server will spawn the projectile. if (m_MagicItem.NetworkInfo != null) { if (m_MagicItem.NetworkInfo.IsLocalPlayer()) { m_MagicItem.NetworkCharacter.MagicCast(m_MagicItem, m_Index, m_CastID, direction, targetPosition); } if (!m_MagicItem.NetworkInfo.IsServer()) { return; } } #endif if (m_ProjectilePrefab == null) { Debug.LogError("Error: A Projectile Prefab must be specified", m_MagicItem); return; } var position = Utility.MathUtility.TransformPoint(origin.position, m_Transform.rotation, m_PositionOffset); var obj = ObjectPoolBase.Instantiate(m_ProjectilePrefab, position, Quaternion.LookRotation(direction, m_CharacterLocomotion.Up) * Quaternion.Euler(m_RotationOffset), m_ParentToOrigin ? origin : null); var projectile = obj.GetComponent <MagicProjectile>(); if (projectile != null) { projectile.Initialize(direction * m_Speed, Vector3.zero, m_GameObject, m_MagicItem, m_CastID); } else { Debug.LogWarning($"Warning: The projectile {m_ProjectilePrefab.name} does not have the MagicProjectile component attached."); } var magicParticle = obj.GetComponent <MagicParticle>(); if (magicParticle != null) { magicParticle.Initialize(m_MagicItem, m_CastID); } #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (m_MagicItem.NetworkInfo != null) { NetworkObjectPool.NetworkSpawn(m_ProjectilePrefab, obj, true); } #endif }
private void DrawObjectPool(ObjectPoolBase objectPool) { GUILayout.Label(Utility.Text.Format("<b>Object Pool: {0}</b>", objectPool.FullName)); GUILayout.BeginVertical("box"); { DrawItem("Name", objectPool.Name); DrawItem("Type", objectPool.ObjectType.FullName); DrawItem("Auto Release Interval", objectPool.AutoReleaseInterval.ToString()); DrawItem("Capacity", objectPool.Capacity.ToString()); DrawItem("Used Count", objectPool.Count.ToString()); DrawItem("Can Release Count", objectPool.CanReleaseCount.ToString()); DrawItem("Expire Time", objectPool.ExpireTime.ToString()); DrawItem("Priority", objectPool.Priority.ToString()); ObjectInfo[] objectInfos = objectPool.GetAllObjectInfos(); GUILayout.BeginHorizontal(); { GUILayout.Label("<b>Name</b>"); GUILayout.Label("<b>Locked</b>", GUILayout.Width(60f)); GUILayout.Label(objectPool.AllowMultiSpawn ? "<b>Count</b>" : "<b>In Use</b>", GUILayout.Width(60f)); GUILayout.Label("<b>Flag</b>", GUILayout.Width(60f)); GUILayout.Label("<b>Priority</b>", GUILayout.Width(60f)); GUILayout.Label("<b>Last Use Time</b>", GUILayout.Width(120f)); } GUILayout.EndHorizontal(); if (objectInfos.Length > 0) { for (int i = 0; i < objectInfos.Length; i++) { GUILayout.BeginHorizontal(); { GUILayout.Label(string.IsNullOrEmpty(objectInfos[i].Name) ? "<None>" : objectInfos[i].Name); GUILayout.Label(objectInfos[i].Locked.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectPool.AllowMultiSpawn ? objectInfos[i].SpawnCount.ToString() : objectInfos[i].IsInUse.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectInfos[i].CustomCanReleaseFlag.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectInfos[i].Priority.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectInfos[i].LastUseTime.ToString("yyyy-MM-dd HH:mm:ss"), GUILayout.Width(120f)); } GUILayout.EndHorizontal(); } } else { GUILayout.Label("<i>Object Pool is Empty ...</i>"); } } GUILayout.EndVertical(); }
public bool Release <T>(string key, T target) where T : Component, new() { ObjectPoolBase pool = null; if (poolDictionary.TryGetValue(key, out pool) == false) { return(false); } ObjectPool <T> componentPool = pool as ObjectPool <T>; if (componentPool == null) { return(false); } return(componentPool.Release(target)); }
private void DrawObjectPool(ObjectPoolBase objectPool) { bool lastState = m_OpenedItems.Contains(objectPool.FullName); bool currentState = EditorGUILayout.Foldout(lastState, objectPool.FullName); if (currentState != lastState) { if (currentState) { m_OpenedItems.Add(objectPool.FullName); } else { m_OpenedItems.Remove(objectPool.FullName); } } if (currentState) { EditorGUILayout.BeginVertical("box"); { EditorGUILayout.LabelField("Name", objectPool.Name); EditorGUILayout.LabelField("Type", objectPool.ObjectType.FullName); EditorGUILayout.LabelField("Auto Release Interval", objectPool.AutoReleaseInterval.ToString()); EditorGUILayout.LabelField("Capacity", objectPool.Capacity.ToString()); EditorGUILayout.LabelField("Used Count", objectPool.Count.ToString()); EditorGUILayout.LabelField("Can Release Count", objectPool.CanReleaseCount.ToString()); EditorGUILayout.LabelField("Expire Time", objectPool.ExpireTime.ToString()); EditorGUILayout.LabelField("Priority", objectPool.Priority.ToString()); ObjectInfo[] objectInfos = objectPool.GetAllObjectInfos(); if (objectInfos.Length > 0) { foreach (ObjectInfo objectInfo in objectInfos) { EditorGUILayout.LabelField(objectInfo.Name, Utility.Text.Format("{0}, {1}, {2}, {3}, {4}", objectInfo.Locked.ToString(), objectPool.AllowMultiSpawn ? objectInfo.SpawnCount.ToString() : objectInfo.IsInUse.ToString(), objectInfo.CustomCanReleaseFlag.ToString(), objectInfo.Priority.ToString(), objectInfo.LastUseTime.ToString("yyyy-MM-dd HH:mm:ss"))); } } else { GUILayout.Label("Object Pool is Empty ..."); } } EditorGUILayout.EndVertical(); EditorGUILayout.Separator(); } }
ObjectPoolBase GetPoolByType(EHudPopupType popupType) { ObjectPoolBase tmpObjPool = null; switch (popupType) { case EHudPopupType.Damage: tmpObjPool = Game.PoolMgr.GetObjectPool <HudPopupDamage>() as ObjectPoolBase; break; default: break; } return(tmpObjPool); }
public override void Dispose() { base.Dispose(); for (int i = mHudPopupList.Count - 1; i >= 0; --i) { var tmpHudPopup = mHudPopupList[i]; ObjectPoolBase tmpPool = GetPoolByType(tmpHudPopup.PopupType); if (null != tmpPool) { tmpPool.Unspawn(tmpHudPopup); } } mHudPopupList.Clear(); }
ObjectPoolBase GetPoolByType(EUnitType unitType) { ObjectPoolBase tmpObjPool = null; switch (unitType) { case EUnitType.EUT_LocalPlayer: tmpObjPool = Game.PoolMgr.GetObjectPool <HudInfoPlayer>() as ObjectPoolBase; break; default: tmpObjPool = Game.PoolMgr.GetObjectPool <HudInfoMonster>() as ObjectPoolBase; break; } return(tmpObjPool); }
HudPopupBase GetPopupInstance(EHudPopupType popupType) { ObjectPoolBase tmpPool = GetPoolByType(popupType); if (null == tmpPool) { return(null); } var tmpHudPopupBase = tmpPool.Spawn2() as HudPopupBase; if (null != tmpHudPopupBase) { tmpHudPopupBase.Initialize(Parent); mHudPopupList.Add(tmpHudPopupBase); } return(tmpHudPopupBase); }
private void DrawObjectPool(ObjectPoolBase objectPool) { GUILayout.Label(string.Format("<b>Object Pool: {0}</b>", string.IsNullOrEmpty(objectPool.Name) ? "<Unnamed>" : objectPool.Name)); GUILayout.BeginVertical("box"); { DrawItem("Type", objectPool.ObjectType.FullName); DrawItem("Auto Release Interval", objectPool.AutoReleaseInterval.ToString()); DrawItem("Capacity", string.Format("{0} / {1} / {2}", objectPool.CanReleaseCount.ToString(), objectPool.Count.ToString(), objectPool.Capacity.ToString())); DrawItem("Expire Time", objectPool.ExpireTime.ToString()); DrawItem("Priority", objectPool.Priority.ToString()); ObjectInfo[] objectInfos = objectPool.GetAllObjectInfos(); GUILayout.BeginHorizontal(); { GUILayout.Label("<b>Name</b>"); GUILayout.Label("<b>Locked</b>", GUILayout.Width(60f)); GUILayout.Label(objectPool.AllowMultiSpawn ? "<b>Count</b>" : "<b>In Use</b>", GUILayout.Width(60f)); GUILayout.Label("<b>Priority</b>", GUILayout.Width(60f)); GUILayout.Label("<b>Last Use Time</b>", GUILayout.Width(120f)); } GUILayout.EndHorizontal(); if (objectInfos.Length > 0) { foreach (ObjectInfo objectInfo in objectInfos) { GUILayout.BeginHorizontal(); { GUILayout.Label(objectInfo.Name); GUILayout.Label(objectInfo.Locked.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectPool.AllowMultiSpawn ? objectInfo.SpawnCount.ToString() : objectInfo.IsInUse.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectInfo.Priority.ToString(), GUILayout.Width(60f)); GUILayout.Label(objectInfo.LastUseTime.ToString("yyyy-MM-dd HH:mm:ss"), GUILayout.Width(120f)); } GUILayout.EndHorizontal(); } } else { GUILayout.Label("<i>Object Pool is Empty ...</i>"); } } GUILayout.EndVertical(); }
/// <summary> /// The magic cast has collided with another object. /// </summary> /// <param name="hit">The raycast that caused the impact.</param> /// <param name="surfaceImpact">The type of particle that collided with the object.</param> private void MagicCastCollision(RaycastHit hit, SurfaceImpact surfaceImpact) { if (m_FlameParticle != null || (m_FlameImpact != null && m_FlameImpact != surfaceImpact)) { return; } // A fireball has collided with the crate. Start the flame. var crateTransform = transform; var flamePrefab = ObjectPoolBase.Instantiate(m_FlamePrefab, crateTransform.position, crateTransform.rotation); m_FlameParticle = flamePrefab.GetComponent <ParticleSystem>(); m_FlameParticleAudioSource = flamePrefab.GetCachedComponent <AudioSource>(); m_FlameParticleAudioSource.volume = 1; m_DamageTrigger.enabled = true; // The crate should be destroyed by the flame. ReduceHealth(); }
public T Create <T>(string key) where T : Component, new() { ObjectPoolBase pool = null; if (poolDictionary.TryGetValue(key, out pool) == false) { return(null); } Type poolType = pool.GetType(); if (poolType == typeof(ObjectPool <T>)) { ObjectPool <T> componentPool = pool as ObjectPool <T>; return(componentPool.Create()); } else { return(null); } }
/// <summary> /// Performs the cast. /// </summary> /// <param name="origin">The location that the cast should spawn from.</param> /// <param name="direction">The direction of the cast.</param> /// <param name="targetPosition">The target position of the cast.</param> public override void Cast(Transform origin, Vector3 direction, Vector3 targetPosition) { if (m_Object == null) { Debug.LogError("Error: An Object must be specified.", m_MagicItem); return; } #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER // The local player will spawn the object if the object is a networked magic object. if (m_MagicItem.NetworkInfo != null && !m_MagicItem.NetworkInfo.IsLocalPlayer()) { if (m_Object.GetComponent <INetworkMagicObject>() != null) { return; } } #endif var position = MathUtility.TransformPoint(origin.position, m_Transform.rotation, m_PositionOffset); if (targetPosition != position) { direction = (targetPosition - position).normalized; } m_SpawnedObject = ObjectPoolBase.Instantiate(m_Object, position, Quaternion.LookRotation(direction, m_CharacterLocomotion.Up) * Quaternion.Euler(m_RotationOffset), m_ParentToOrigin ? origin : null); #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (m_MagicItem.NetworkInfo != null && m_MagicItem.NetworkInfo.IsLocalPlayer()) { var networkMagicObject = m_SpawnedObject.GetComponent <INetworkMagicObject>(); if (networkMagicObject != null) { networkMagicObject.Instantiate(m_GameObject, m_MagicItem, m_Index, m_CastID); } NetworkObjectPool.NetworkSpawn(m_Object, m_SpawnedObject, false); } #endif }
/// <summary> /// The object has been picked up. /// </summary> /// <param name="pickedUpBy">A reference to the object that picked up the object.</param> protected virtual void ObjectPickedUp(GameObject pickedUpBy) { // The object may not have been instantiated within the scene. if (m_GameObject == null) { return; } m_IsDepleted = true; // Send an event notifying of the pickup. EventHandler.ExecuteEvent(pickedUpBy, "OnObjectPickedUp", this); // Optionally play a pickup sound if the object picking up the item is attached to a camera. // A null GameObject indicates that the clip will play from the AudioManager. var foundCamera = Shared.Camera.CameraUtility.FindCamera(pickedUpBy); if (foundCamera != null) { m_PickupAudioClipSet.PlayAtPosition(m_Transform.position); } if (ObjectPoolBase.InstantiatedWithPool(m_GameObject)) { #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (NetworkObjectPool.IsNetworkActive()) { NetworkObjectPool.Destroy(m_GameObject); return; } #endif ObjectPoolBase.Destroy(m_GameObject); } else { // Deactivate the pickup for now. It can appear again if a Respawner component is attached to the GameObject. m_GameObject.SetActive(false); } }
/// <summary> /// Spawns the particle. /// </summary> /// <param name="origin">The location that the cast originates from.</param> private void Spawn(Transform origin) { if (m_ParticlePrefab == null) { Debug.LogError("Error: A Particle Prefab must be specified.", m_MagicItem); return; } var obj = ObjectPoolBase.Instantiate(m_ParticlePrefab, MathUtility.TransformPoint(origin.position, m_Transform.rotation, m_PositionOffset), origin.rotation * Quaternion.Euler(m_RotationOffset), m_ParentToOrigin ? origin : null); m_SpawnedTransform = obj.transform; var particleSystem = obj.GetCachedComponent <ParticleSystem>(); if (particleSystem == null) { Debug.LogError($"Error: A Particle System must be specified on the particle {m_ParticlePrefab}.", m_MagicItem); return; } particleSystem.Clear(true); }
/// <summary> /// Instantiates a new decal. /// </summary> /// <param name="original">The original prefab to spawn an instance of.</param> /// <param name="hit">The RaycastHit which caused the footprint to spawn.</param> /// <param name="rotation">The rotation of the decal which should be spawned.</param> /// <param name="scale">The scale of the decal to spawn.</param> /// <param name="allowedEdgeOverlap">How close to the edge the footprint is allowed to spawn.</param> /// <returns>The spawned decal. Can be null.</returns> private GameObject SpawnDecal(GameObject original, RaycastHit hit, Quaternion rotation, float scale, float allowedEdgeOverlap) { // Prevent z fighting by slightly raising the decal off of the surface. var decal = ObjectPoolBase.Instantiate(original, hit.point + (hit.normal * 0.001f), rotation); // Only set the decal parent to the hit transform on uniform objects to prevent stretching. if (MathUtility.IsUniform(hit.transform.localScale)) { decal.transform.parent = hit.transform; } if (scale != 1) { var vectorScale = Vector3.one; vectorScale.x = vectorScale.y = scale; decal.transform.localScale = vectorScale; } // Destroy the object if it cannot be cached. The object won't be able to be cached if it doesn't have all of the required components. if (!CacheMeshAndRenderer(decal)) { ObjectPoolBase.Destroy(decal); return(null); } // Do a test on the decal's quad to ensure all four corners are flush against a surface. This will prevent the decal from sticking out on an edge. if (allowedEdgeOverlap < 0.5f) { if (!DoQuadTest(decal, allowedEdgeOverlap)) { ObjectPoolBase.Destroy(decal); return(null); } } // The decal can be added. Add(decal); return(decal); }
/// <summary> /// Stops the cast. /// </summary> public override void Stop() { if (m_SpawnedObject != null) { #if ULTIMATE_CHARACTER_CONTROLLER_MULTIPLAYER if (NetworkObjectPool.IsNetworkActive()) { // The object may have already been destroyed over the network. if (!m_GameObject.activeSelf) { return; } NetworkObjectPool.Destroy(m_SpawnedObject); return; } #endif ObjectPoolBase.Destroy(m_SpawnedObject); m_SpawnedObject = null; } base.Stop(); }