public void WhenDestroyed(DestructionInfo info) { // rare cases were gameObject is destroyed for some reason and then the method is called if (gameObject == null) { return; } Inventory.ServerSpawnPrefab(powerControlModule, powerControlSlot, ReplacementStrategy.Cancel); Inventory.ServerSpawnPrefab(powerCell, powerCellSlot, ReplacementStrategy.Cancel); SpawnResult frameSpawn = Spawn.ServerPrefab(APCFrameObj, SpawnDestination.At(gameObject)); if (frameSpawn.Successful == false) { Logger.LogError($"Failed to spawn frame! Is {this} missing references in the inspector?", Category.Construction); return; } GameObject frame = frameSpawn.GameObject; frame.GetComponent <APCFrame>().ServerInitFromComputer(this); var Directional = frame.GetComponent <Directional>(); if (Directional != null) { Directional.FaceDirection(gameObject.GetComponent <Directional>().CurrentDirection); } _ = Despawn.ServerSingle(gameObject); integrity.OnWillDestroyServer.RemoveListener(WhenDestroyed); }
/// <summary> /// Finish cooking the microwaved meal. /// </summary> private void FinishCooking() { spriteRenderer.sprite = SPRITE_OFF; if (isServer) { GameObject mealPrefab = CraftingManager.Meals.FindOutputMeal(meal); SpawnResult result = Spawn.ServerPrefab(mealPrefab, GetComponent <RegisterTile>().WorldPosition, transform.parent); //If the resulting meal has a stackable component, set the amount to mealCount to ensure that food in = food out. Stackable stck = result.GameObject.GetComponent <Stackable>(); if (stck != null && mealCount != 0) { //Get difference between new item's initial amount and the amount held by mealCount (amount of ingredient). int stckChanger = mealCount - stck.Amount; //If stckChanger is 0, do nothing. //If stckChanger is positive, add to stack. if (stckChanger > 0) { stck.ServerIncrease(stckChanger); } else if (stckChanger < 0) { //If stckChanger is positive, remove stack. stck.ServerConsume(-stckChanger); } } } meal = null; mealCount = 0; }
public void WhenDestroyed(DestructionInfo info) { //drop all our contents ItemStorage itemStorage = null; // rare cases were gameObject is destroyed for some reason and then the method is called if (gameObject == null) { return; } itemStorage = GetComponent <ItemStorage>(); if (itemStorage != null) { itemStorage.ServerDropAll(); } SpawnResult frameSpawn = Spawn.ServerPrefab(CommonPrefabs.Instance.MachineFrame, SpawnDestination.At(gameObject)); if (!frameSpawn.Successful) { Logger.LogError($"Failed to spawn frame! Is {this} missing references in the inspector?", Category.Construction); return; } GameObject frame = frameSpawn.GameObject; frame.GetComponent <MachineFrame>().ServerInitFromComputer(this); Despawn.ServerSingle(gameObject); integrity.OnWillDestroyServer.RemoveListener(WhenDestroyed); }
/// <summary> /// Server-side only. Performs the spawn and syncs it to all clients. /// </summary> /// <returns></returns> private static SpawnResult Server(SpawnInfo info, bool AutoOnSpawnServerHook = true) { if (info == null) { Logger.LogError("Cannot spawn, info is null", Category.ItemSpawn); return(SpawnResult.Fail(info)); } EnsureInit(); Logger.LogTraceFormat("Server spawning {0}", Category.ItemSpawn, info); List <GameObject> spawnedObjects = new List <GameObject>(); for (int i = 0; i < info.Count; i++) { var result = info.SpawnableToSpawn.SpawnAt(info.SpawnDestination); if (result.Successful) { spawnedObjects.Add(result.GameObject); //apply scattering if it was specified if (info.ScatterRadius != null) { foreach (var spawned in spawnedObjects) { var cnt = spawned.GetComponent <CustomNetTransform>(); var scatterRadius = info.ScatterRadius.GetValueOrDefault(0); if (cnt != null) { cnt.SetPosition(info.SpawnDestination.WorldPosition + new Vector3(Random.Range(-scatterRadius, scatterRadius), Random.Range(-scatterRadius, scatterRadius))); } } } } else { return(SpawnResult.Fail(info)); } } //fire hooks for all spawned objects SpawnResult spawnResult = null; if (spawnedObjects.Count == 1) { spawnResult = SpawnResult.Single(info, spawnedObjects[0]); } else { spawnResult = SpawnResult.Multiple(info, spawnedObjects); } if (AutoOnSpawnServerHook) { _ServerFireClientServerSpawnHooks(spawnResult); } return(spawnResult); }
/// <summary> /// Performs the specified spawn locally, for this client only. Must not be called on /// networked objects (objects with NetworkIdentity), or you will get unpredictable behavior. /// </summary> /// <returns></returns> public static SpawnResult Client(SpawnInfo info) { if (info == null) { Logger.LogError("Cannot spawn, info is null", Category.ItemSpawn); return(SpawnResult.Fail(info)); } if (info.SpawnableToSpawn is IClientSpawnable clientSpawnable) { List <GameObject> spawnedObjects = new List <GameObject>(); for (var i = 0; i < info.Count; i++) { var result = clientSpawnable.ClientSpawnAt(info.SpawnDestination); if (result.Successful) { spawnedObjects.Add(result.GameObject); } } if (spawnedObjects.Count == 1) { return(SpawnResult.Single(info, spawnedObjects[0])); } return(SpawnResult.Multiple(info, spawnedObjects)); } else { Logger.LogErrorFormat("Cannot spawn {0} client side, spawnable does not" + " implement IClientSpawnable", Category.ItemSpawn, info); return(SpawnResult.Fail(info)); } }
public void Dispense(GameObject objectPrefab, PipeLayer pipeLayer, Color pipeColor) { if (MachineOperating || securable.IsAnchored == false) { return; } this.RestartCoroutine(SetMachineOperating(), ref animationRoutine); SpawnResult spawnResult = Spawn.ServerPrefab(objectPrefab, objectBehaviour.AssumedWorldPositionServer()); if (spawnResult.Successful) { spawnResult.GameObject.GetComponent <PipeItem>()?.SetColour(pipeColor); newPipe = new PipeObjectSettings { pipeObject = spawnResult.GameObject, pipeColor = pipeColor }; } else { Logger.LogError($"Failed to spawn an object from {name}! Is GUI_{name} missing reference to object prefab?", Category.Pipes); } }
public void ServerPerformInteraction(InventoryApply interaction) { //is the target item chopable? ItemAttributesV2 attr = interaction.TargetObject.GetComponent <ItemAttributesV2>(); Ingredient ingredient = new Ingredient(attr.ArticleName); GameObject cut = CraftingManager.Logs.FindRecipe(new List <Ingredient> { ingredient }); if (cut != null) { Inventory.ServerDespawn(interaction.TargetSlot); SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.Logs.FindOutputMeal(cut.name), SpawnDestination.At(), 1); if (spwn.Successful) { //foreach (GameObject obj in spwn.GameObjects) //{ // Inventory.ServerAdd(obj,interaction.TargetSlot); //} Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot); } } else { Chat.AddExamineMsgFromServer(interaction.Performer, "You can't chop this."); } }
public void ServerPerformInteraction(InventoryApply interaction) { //is the target item cuttable? ItemAttributesV2 attr = interaction.TargetObject.GetComponent <ItemAttributesV2>(); Ingredient ingredient = new Ingredient(attr.ArticleName); GameObject roll = CraftingManager.Roll.FindRecipe(new List <Ingredient> { ingredient }); if (roll) { Inventory.ServerDespawn(interaction.TargetSlot); SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.Roll.FindOutputMeal(roll.name), SpawnDestination.At(), 1); if (spwn.Successful) { Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot); } } else { Chat.AddExamineMsgFromServer(interaction.Performer, "You can't roll this out."); } }
public void Dispense(GameObject objectPrefab, PipeLayer pipeLayer, Color pipeColor) { if (MachineOperating || securable.IsAnchored == false) { return; } this.RestartCoroutine(SetMachineOperating(), ref animationRoutine); SpawnResult spawnResult = Spawn.ServerPrefab(objectPrefab, objectBehaviour.AssumedWorldPositionServer()); if (spawnResult.Successful == false) { Logger.LogError( $"Failed to spawn an object from {name}! " + $"Is {nameof(UI.Objects.Atmospherics.GUI_PipeDispenser)} missing reference to object prefab?", Category.Pipes); return; } foreach (var spriteHandler in spawnResult.GameObject.GetComponentsInChildren <SpriteHandler>()) { spriteHandler.SetColor(pipeColor); } if (spawnResult.GameObject.TryGetComponent <PipeItem>(out var pipe)) { pipe.Colour = pipeColor; } }
//Force use through Fail protected DefaultEntitySpawnDetails(SpawnResult failureReason) { if (failureReason == SpawnResult.Success) { throw new ArgumentException($"Provided {nameof(SpawnResult)} was successful but should have been a failure."); } Result = failureReason; }
/// <summary> /// Spawns a new player character and transfers the connection's control into the new body. /// If existingMind is null, creates the new mind and assigns it to the new body. /// /// Fires server and client side player spawn hooks. /// </summary> /// <param name="connection">connection to give control to the new player character</param> /// <param name="occupation">occupation of the new player character</param> /// <param name="characterSettings">settings of the new player character</param> /// <param name="existingMind">existing mind to transfer to the new player, if null new mind will be created /// and assigned to the new player character</param> /// <param name="spawnPos">world position to spawn at</param> /// <param name="naked">If spawning a player, should the player spawn without the defined initial equipment for their occupation?</param> /// <param name="willDestroyOldBody">if true, indicates the old body is going to be destroyed rather than pooled, /// thus we shouldn't send any network message which reference's the old body's ID since it won't exist.</param> /// /// <returns>the spawned object</returns> private static GameObject ServerSpawnInternal(NetworkConnection connection, Occupation occupation, CharacterSettings characterSettings, Mind existingMind, Vector3Int?spawnPos = null, bool naked = false, bool willDestroyOldBody = false) { //determine where to spawn them if (spawnPos == null) { Transform spawnTransform = GetSpawnForJob(occupation.JobType); if (spawnTransform == null) { Logger.LogErrorFormat( "Unable to determine spawn position for connection {0} occupation {1}. Cannot spawn player.", Category.ItemSpawn, connection.address, occupation.DisplayName); return(null); } spawnPos = spawnTransform.transform.position.CutToInt(); } //create the player object var newPlayer = ServerCreatePlayer(spawnPos.GetValueOrDefault()); var newPlayerScript = newPlayer.GetComponent <PlayerScript>(); //get the old body if they have one. var oldBody = existingMind?.GetCurrentMob(); //transfer control to the player object ServerTransferPlayer(connection, newPlayer, oldBody, EVENT.PlayerSpawned, characterSettings, willDestroyOldBody); if (existingMind == null) { //create the mind of the player Mind.Create(newPlayer, occupation); } else { //transfer the mind to the new body existingMind.SetNewBody(newPlayerScript); } var ps = newPlayer.GetComponent <PlayerScript>(); var connectedPlayer = PlayerList.Instance.Get(connection); connectedPlayer.Name = ps.playerName; connectedPlayer.Job = ps.mind.occupation.JobType; UpdateConnectedPlayersMessage.Send(); //fire all hooks var info = SpawnInfo.Player(occupation, characterSettings, CustomNetworkManager.Instance.humanPlayerPrefab, SpawnDestination.At(spawnPos), naked: naked); Spawn._ServerFireClientServerSpawnHooks(SpawnResult.Single(info, newPlayer)); return(newPlayer); }
private void SpawnContagionSpot(SymptomManifestation symptomManifestation, Vector3 position) { SpawnResult spawnResult = Spawn.ServerPrefab(contagionPrefab, position, null, null, 1, null, true); if (spawnResult.Successful) { spawnResult.GameObject.GetComponent <Contagion>().Sickness = symptomManifestation.SicknessAffliction.Sickness; } }
public static GameObject SpawnVirtualContainer(Vector3Int worldPosition) { SpawnResult virtualContainerSpawn = Spawn.ServerPrefab(Instance.VirtualContainerPrefab, worldPosition); if (!virtualContainerSpawn.Successful) { Logger.LogError( "Failed to spawn disposal virtual container! " + $"Is {nameof(DisposalsManager)} missing reference to {nameof(Instance.VirtualContainerPrefab)}?"); return(default);
/// <summary> /// NOTE: For internal lifecycle system use only. /// /// Fires all the server side spawn hooks for the given spawn and messages all clients telling them to fire their /// client-side hooks. Should only be called after object becomes networked / known by clients. /// </summary> /// <param name="result"></param> public static void _ServerFireClientServerSpawnHooks(SpawnResult result) { //fire server hooks foreach (var spawnedObject in result.GameObjects) { var comps = spawnedObject.GetComponentsInChildren <IServerSpawn>(); foreach (var comp in comps) { comp.OnSpawnServer(result.SpawnInfo); } } }
private void PerformCut(InventoryApply interaction, GameObject cut) { Inventory.ServerDespawn(interaction.TargetSlot); SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.Cuts.FindOutputMeal(cut.name), SpawnDestination.At(), 1); if (spwn.Successful) { Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot); } }
/// <summary> /// Inform all clients about this spawn event /// </summary> /// <param name="result">results of the spawn that was already performed server side</param> /// <returns></returns> public static void SendToAll(SpawnResult result) { foreach (var spawnedObject in result.GameObjects) { SpawnMessage msg = new SpawnMessage { SpawnedObject = spawnedObject.NetId(), ClonedFrom = result.SpawnInfo.SpawnType == SpawnType.Clone ? result.SpawnInfo.ClonedFrom.NetId() : NetId.Invalid }; msg.SendToAll(); } }
public DefaultEntitySpawnDetails(GameObject gameObject) { if (gameObject == null) { throw new ArgumentNullException(nameof(gameObject), $"Provided {nameof(gameObject)} {nameof(GameObject)} argument must not be null."); } EntityGameObject = gameObject; //alaways success if provided game object Result = SpawnResult.Success; }
/// <summary> /// Spawns a ghost for the indicated mind's body and transfers the connection's control to it. /// </summary> /// <param name="conn"></param> /// <param name="oldBody"></param> /// <param name="characterSettings"></param> /// <param name="occupation"></param> /// <returns></returns> public static void ServerSpawnGhost(Mind forMind) { //determine where to spawn the ghost var body = forMind.GetCurrentMob(); var settings = body.GetComponent <PlayerScript>().characterSettings; var connection = body.GetComponent <NetworkIdentity>().connectionToClient; var registerTile = body.GetComponent <RegisterTile>(); if (registerTile == null) { Logger.LogErrorFormat("Cannot spawn ghost for body {0} because it has no registerTile", Category.ItemSpawn, body.name); return; } Vector3Int spawnPosition = body.GetComponent <ObjectBehaviour>().AssumedWorldPositionServer().RoundToInt(); if (spawnPosition == TransformState.HiddenPos) { //spawn ghost at occupation location if we can't determine where their body is Transform spawnTransform = GetSpawnForJob(forMind.occupation.JobType); if (spawnTransform == null) { Logger.LogErrorFormat("Unable to determine spawn position for occupation {1}. Cannot spawn ghost.", Category.ItemSpawn, forMind.occupation.DisplayName); return; } spawnPosition = spawnTransform.transform.position.CutToInt(); } var matrixInfo = MatrixManager.AtPoint(spawnPosition, true); var parentNetId = matrixInfo.NetID; var parentTransform = matrixInfo.Objects; //using parentTransform.rotation rather than Quaternion.identity because objects should always //be upright w.r.t. localRotation, NOT world rotation var ghost = Object.Instantiate(CustomNetworkManager.Instance.ghostPrefab, spawnPosition, parentTransform.rotation, parentTransform); ghost.GetComponent <PlayerScript>().registerTile.ServerSetNetworkedMatrixNetID(parentNetId); forMind.Ghosting(ghost); ServerTransferPlayer(connection, ghost, body, EVENT.GhostSpawned, settings); //fire all hooks var info = SpawnInfo.Ghost(forMind.occupation, settings, CustomNetworkManager.Instance.ghostPrefab, SpawnDestination.At(spawnPosition, parentTransform)); Spawn._ServerFireClientServerSpawnHooks(SpawnResult.Single(info, ghost)); }
private bool SpawnGunInHand(ConnectedPlayer caster) { SpawnResult result = Spawn.ServerPrefab(gunPrefab, caster.Script.WorldPos); if (result.Successful) { GameObject firstGun = result.GameObject; ItemSlot bestSlot = caster.Script.ItemStorage.GetBestHandOrSlotFor(firstGun); Inventory.ServerAdd(firstGun, bestSlot); return(true); } Logger.LogError($"Failed to spawn {gunPrefab} for {this}!"); return(false); }
/// <summary> /// Performs the specified spawn locally, for this client only. /// </summary> /// <returns></returns> public static SpawnResult Client(SpawnInfo info) { if (info == null) { Logger.LogError("Cannot spawn, info is null", Category.ItemSpawn); return(SpawnResult.Fail(info)); } if (info.SpawnableToSpawn is IClientSpawnable clientSpawnable) { List <GameObject> spawnedObjects = new List <GameObject>(); for (var i = 0; i < info.Count; i++) { var result = clientSpawnable.ClientSpawnAt(info.SpawnDestination); if (result.Successful) { spawnedObjects.Add(result.GameObject); } } //fire client side lifecycle hooks foreach (var spawnedObject in spawnedObjects) { var hooks = spawnedObject.GetComponents <IClientSpawn>(); if (hooks != null) { foreach (var hook in hooks) { hook.OnSpawnClient(ClientSpawnInfo.Default()); } } } if (spawnedObjects.Count == 1) { return(SpawnResult.Single(info, spawnedObjects[0])); } return(SpawnResult.Multiple(info, spawnedObjects)); } else { Logger.LogErrorFormat("Cannot spawn {0} client side, spawnable does not" + " implement IClientSpawnable", Category.ItemSpawn, info); return(SpawnResult.Fail(info)); } }
/// <summary> /// Spawns an assistant dummy /// </summary> public static void ServerSpawnDummy() { Transform spawnTransform = GetSpawnForJob(JobType.ASSISTANT); if (spawnTransform != null) { var dummy = ServerCreatePlayer(spawnTransform.position.RoundToInt()); ServerTransferPlayer(null, dummy, null, EVENT.PlayerSpawned, new CharacterSettings()); //fire all hooks var info = SpawnInfo.Player(OccupationList.Instance.Get(JobType.ASSISTANT), new CharacterSettings(), CustomNetworkManager.Instance.humanPlayerPrefab, SpawnDestination.At(spawnTransform.gameObject)); Spawn._ServerFireClientServerSpawnHooks(SpawnResult.Single(info, dummy)); } }
/// <summary> /// NOTE: For internal lifecycle system use only. /// /// Fires all the server side spawn hooks for the given spawn and messages all clients telling them to fire their /// client-side hooks. Should only be called after object becomes networked / known by clients. /// </summary> /// <param name="result"></param> public static void _ServerFireClientServerSpawnHooks(SpawnResult result) { //fire server hooks foreach (var spawnedObject in result.GameObjects) { var comps = spawnedObject.GetComponents <IServerSpawn>(); if (comps != null) { foreach (var comp in comps) { comp.OnSpawnServer(result.SpawnInfo); } } } //fire client hooks SpawnMessage.SendToAll(result); }
void ServerInit(MatrixInfo matrixInfo) { SpawnResult traySpawn = Spawn.ServerPrefab(trayPrefab, DrawerWorldPosition); if (!traySpawn.Successful) { throw new MissingReferenceException($"Failed to spawn tray! Is {name} prefab missing reference to tray prefab?"); } tray = traySpawn.GameObject; traySpriteHandler = tray.GetComponentInChildren<SpriteHandler>(); trayTransform = tray.GetComponent<CustomNetTransform>(); trayBehaviour = tray.GetComponent<ObjectBehaviour>(); trayBehaviour.parentContainer = drawerPushPull; trayBehaviour.VisibleState = false; // These two will sync drawer state/orientation and render appropriate sprite drawerState = DrawerState.Shut; drawerOrientation = directional.CurrentDirection; }
/// <summary> /// Performs the specified spawn locally, for this client only. /// </summary> /// <returns></returns> public static SpawnResult Client(SpawnInfo info) { if (info == null) { Logger.LogError("Cannot spawn, info is null", Category.ItemSpawn); return(SpawnResult.Fail(info)); } List <GameObject> spawnedObjects = new List <GameObject>(); for (var i = 0; i < info.Count; i++) { if (info.SpawnableType == SpawnableType.Cloth) { Logger.LogErrorFormat("Spawning cloths on client side is not currently supported. {0}", Category.ItemSpawn, info); return(SpawnResult.Fail(info)); } bool isPooled; // not used for Client-only instantiation var go = PoolInstantiate(info.PrefabUsed, info.WorldPosition, info.Rotation, info.Parent, out isPooled); spawnedObjects.Add(go); } //fire client side lifecycle hooks foreach (var spawnedObject in spawnedObjects) { var hooks = spawnedObject.GetComponents <IClientSpawn>(); if (hooks != null) { foreach (var hook in hooks) { hook.OnSpawnClient(ClientSpawnInfo.Default()); } } } if (spawnedObjects.Count == 1) { return(SpawnResult.Single(info, spawnedObjects[0])); } return(SpawnResult.Multiple(info, spawnedObjects)); }
public void ServerPerformInteraction(InventoryApply interaction) { //is the target item another ingredient? ItemAttributesV2 attr = interaction.TargetObject.GetComponent <ItemAttributesV2>(); ItemAttributesV2 selfattr = interaction.UsedObject.GetComponent <ItemAttributesV2>(); Ingredient ingredient = new Ingredient(attr.ArticleName); Ingredient self = new Ingredient(selfattr.ArticleName); GameObject cut = CraftingManager.SimpleMeal.FindRecipe(new List <Ingredient> { ingredient, self }); GameObject cut2 = CraftingManager.SimpleMeal.FindRecipe(new List <Ingredient> { self, ingredient }); if (cut) { Inventory.ServerDespawn(interaction.TargetObject); Inventory.ServerDespawn(interaction.UsedObject); SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.SimpleMeal.FindOutputMeal(cut.name), SpawnDestination.At(), 1); if (spwn.Successful) { Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot); } } else if (cut2) { Inventory.ServerDespawn(interaction.TargetSlot); Inventory.ServerDespawn(interaction.Performer); SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.SimpleMeal.FindOutputMeal(cut2.name), SpawnDestination.At(), 1); if (spwn.Successful) { Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot); } } }
/// <summary> /// Finish cooking the microwaved meal. /// </summary> private void FinishCooking() { spriteRenderer.sprite = SPRITE_OFF; if (isServer && mealCount > 0) { GameObject mealPrefab = CraftingManager.Meals.FindOutputMeal(meal); Vector3Int spawnPosition = GetComponent <RegisterTile>().WorldPosition; SpawnResult result = Spawn.ServerPrefab(mealPrefab, spawnPosition, transform.parent); Stackable stck = result.GameObject.GetComponent <Stackable>(); if (stck != null) // If the meal has a stackable component, set the correct number of meals { int mealDeficit = mealCount - stck.InitialAmount; while (mealDeficit > 0) { mealDeficit = stck.ServerIncrease(mealDeficit); if (mealDeficit > 0) { result = Spawn.ServerPrefab(mealPrefab, spawnPosition, transform.parent); stck = result.GameObject.GetComponent <Stackable>(); mealDeficit -= stck.InitialAmount; } } if (mealDeficit < 0) // Reduce the stack if our last spawned stackable results in too many meals { stck.ServerConsume(-mealDeficit); } } else if (mealCount > 1) // Spawn non-stackable meals { Spawn.ServerPrefab(mealPrefab, spawnPosition, transform.parent, count: mealCount - 1); } } meal = null; mealCount = 0; }
void ServerInit(MatrixInfo matrixInfo) { SpawnResult traySpawn = Spawn.ServerPrefab(trayPrefab, DrawerWorldPosition); if (!traySpawn.Successful) { Logger.LogError($"Failed to spawn tray! Is {name} prefab missing reference to {nameof(traySpawn)} prefab?"); return; } tray = traySpawn.GameObject; tray.GetComponent <InteractableDrawerTray>().parentDrawer = this; traySpriteHandler = tray.GetComponentInChildren <SpriteHandler>(); trayTransform = tray.GetComponent <CustomNetTransform>(); trayBehaviour = tray.GetComponent <ObjectBehaviour>(); trayBehaviour.parentContainer = drawerPushPull; trayBehaviour.VisibleState = false; UpdateSpriteState(); UpdateSpriteOrientation(); }
private void Flip() { SpawnResult flippedObjectSpawn = Spawn.ServerPrefab(flippedObject, gameObject.RegisterTile().WorldPositionServer); if (flippedObjectSpawn.Successful) { if (flippedObjectSpawn.GameObject.TryGetComponent(out Directional directional)) { var initialOrientation = directional.CurrentDirection; directional.FaceDirection(initialOrientation); } Despawn.ServerSingle(gameObject); } else { Logger.LogError( $"Failed to spawn {name}'s flipped version! " + $"Is {name} missing reference to {nameof(flippedObject)} prefab?"); } }
/// <summary> /// Spawns an assistant dummy /// </summary> public static void ServerSpawnDummy(Transform spawnTransform = null) { if (spawnTransform == null) { spawnTransform = SpawnPoint.GetRandomPointForJob(JobType.ASSISTANT); } if (spawnTransform != null) { var dummy = ServerCreatePlayer(spawnTransform.position.RoundToInt()); CharacterSettings randomSettings = CharacterSettings.RandomizeCharacterSettings(); ServerTransferPlayer(null, dummy, null, Event.PlayerSpawned, randomSettings); //fire all hooks var info = SpawnInfo.Player(OccupationList.Instance.Get(JobType.ASSISTANT), randomSettings, CustomNetworkManager.Instance.humanPlayerPrefab, SpawnDestination.At(spawnTransform.gameObject)); Spawn._ServerFireClientServerSpawnHooks(SpawnResult.Single(info, dummy)); } }
IEnumerator SpawnEnemiesNow() { foreach (SpawnArea area in spawnAreas) { for (int i = 0; i < area.numberToSpawn; i++) { float y = area.spawnLocation.position.y; ScaleToYaxis(y, area.typeOfStatDrop); if (y < 20f) // easy ScaleEnemyToWeaponType(1, area.typeOfStatDrop); else if (y > 20f && y < 80f) // moderate ScaleEnemyToWeaponType(1.5f, area.typeOfStatDrop); else if (y > 80f && y < 170f) // hard ScaleEnemyToWeaponType(3f, area.typeOfStatDrop); else if (y > 170f) ScaleEnemyToWeaponType(4f, area.typeOfStatDrop); if (area.typeOfEnemy == TypeOfEnemy.Skeleton) { SpawnResult result = new SpawnResult(); var skeleton = CreateSkeleton(area.prefab, area.spawnLocation.position + new Vector3(i, i, 0f), HP_Median, Atk_Median, Def_Median, AmountOfStatToGive, area.typeOfStatDrop); skeleton.Spawner = this; result.enemy = skeleton; //polymorphism, reference this skeleton to compare later result.source = area; // reference this area values for respawning spawnResults.Add(result); // add enemy to the list of spawned enemies } if (area.townSkeleton) yield return new WaitForSeconds(UnityEngine.Random.Range(2f, 5f)); } yield return null; } }
IEnumerator SpawnEnemiesNow() { for (int u = 0; u < spawnAreas.Count; u++) { for (int i = 0; i < spawnAreas[u].numberToSpawn; i++) { int r1 = UnityEngine.Random.Range(1, 4); switch (r1) { case 1: spawnAreas[u].typeOfStatDrop = TypeOfStatIncrease.HP; break; case 2: spawnAreas[u].typeOfStatDrop = TypeOfStatIncrease.ATK; break; case 3: spawnAreas[u].typeOfStatDrop = TypeOfStatIncrease.DEF; break; default: spawnAreas[u].typeOfStatDrop = TypeOfStatIncrease.HP; break; } float y = spawnAreas[u].spawnLocation.position.y; //ScaleToYaxis(y, spawnAreas[u]); SpawnArea tempArea = new SpawnArea(); if (y < 20f) // easy tempArea = ScaleEnemyToWeaponType(1, spawnAreas[u]); else if (y > 20f && y < 80f) // moderate tempArea = ScaleEnemyToWeaponType(2f, spawnAreas[u]); else if (y > 80f && y < 170f) // hard tempArea = ScaleEnemyToWeaponType(3f, spawnAreas[u]); else if (y > 170f) tempArea = ScaleEnemyToWeaponType(4f, spawnAreas[u]); if (spawnAreas[u].typeOfEnemy == TypeOfEnemy.Skeleton) { SpawnResult result = new SpawnResult(); var skeleton = CreateSkeleton(spawnAreas[u].prefab, spawnAreas[u].spawnLocation.position + new Vector3(i, i, 0f), HP_Median, Atk_Median, Def_Median, tempArea.amountOfStatToGive, spawnAreas[u].typeOfStatDrop); skeleton.Spawner = this; result.enemy = skeleton; result.source = spawnAreas[u]; spawnResults.Add(result); // add enemy to the list of spawned enemies } yield return new WaitForSeconds(0.05f); } yield return null; } }
IEnumerator RespawnEnemy(SpawnResult sr) { float r = UnityEngine.Random.Range(30f, 120f); yield return new WaitForSeconds(r); int r1 = UnityEngine.Random.Range(1, 6); switch (r1) { case 1: sr.source.typeOfStatDrop = TypeOfStatIncrease.HP; break; case 2: case 3: sr.source.typeOfStatDrop = TypeOfStatIncrease.ATK; break; case 4: sr.source.typeOfStatDrop = TypeOfStatIncrease.DEF; break; default: sr.source.typeOfStatDrop = TypeOfStatIncrease.HP; break; } float y = sr.source.spawnLocation.position.y; ScaleToYaxis(y, sr.source); if (sr.source.typeOfEnemy == TypeOfEnemy.Skeleton) { SpawnResult result = new SpawnResult(); var skeleton = CreateSkeleton(sr.source.prefab, sr.source.spawnLocation.position, HP_Median, Atk_Median, Def_Median, AmountOfStatToGive, sr.source.typeOfStatDrop); skeleton.Spawner = this; result.enemy = skeleton; //polymorphism, reference this skeleton to compare later result.source = sr.source; // reference this area values for respawning spawnResults[spawnResults.IndexOf(sr)] = result; // assign new enemy into dead enemy's index in the list } }
/// <summary> /// Spawns a new player character and transfers the connection's control into the new body. /// If existingMind is null, creates the new mind and assigns it to the new body. /// /// Fires server and client side player spawn hooks. /// </summary> /// <param name="connection">connection to give control to the new player character</param> /// <param name="occupation">occupation of the new player character</param> /// <param name="characterSettings">settings of the new player character</param> /// <param name="existingMind">existing mind to transfer to the new player, if null new mind will be created /// and assigned to the new player character</param> /// <param name="spawnPos">world position to spawn at</param> /// <param name="spawnItems">If spawning a player, should the player spawn without the defined initial equipment for their occupation?</param> /// <param name="willDestroyOldBody">if true, indicates the old body is going to be destroyed rather than pooled, /// thus we shouldn't send any network message which reference's the old body's ID since it won't exist.</param> /// /// <returns>the spawned object</returns> private static GameObject ServerSpawnInternal(NetworkConnection connection, Occupation occupation, CharacterSettings characterSettings, Mind existingMind, Vector3Int?spawnPos = null, bool spawnItems = true, bool willDestroyOldBody = false) { //determine where to spawn them if (spawnPos == null) { Transform spawnTransform; //Spawn normal location for special jobs or if less than 2 minutes passed if (GameManager.Instance.stationTime < ARRIVALS_SPAWN_TIME || occupation.LateSpawnIsArrivals == false) { spawnTransform = GetSpawnForJob(occupation.JobType); } else { spawnTransform = GetSpawnForLateJoin(occupation.JobType); //Fallback to assistant spawn location if none found for late join if (spawnTransform == null && occupation.JobType != JobType.NULL) { spawnTransform = GetSpawnForJob(JobType.ASSISTANT); } } if (spawnTransform == null) { Logger.LogErrorFormat( "Unable to determine spawn position for connection {0} occupation {1}. Cannot spawn player.", Category.ItemSpawn, connection.address, occupation.DisplayName); return(null); } spawnPos = spawnTransform.transform.position.CutToInt(); } //create the player object var newPlayer = ServerCreatePlayer(spawnPos.GetValueOrDefault()); var newPlayerScript = newPlayer.GetComponent <PlayerScript>(); //get the old body if they have one. var oldBody = existingMind?.GetCurrentMob(); //transfer control to the player object ServerTransferPlayer(connection, newPlayer, oldBody, EVENT.PlayerSpawned, characterSettings, willDestroyOldBody); if (existingMind == null) { //create the mind of the player Mind.Create(newPlayer, occupation); } else { //transfer the mind to the new body existingMind.SetNewBody(newPlayerScript); } var ps = newPlayer.GetComponent <PlayerScript>(); var connectedPlayer = PlayerList.Instance.Get(connection); connectedPlayer.Name = ps.playerName; connectedPlayer.Job = ps.mind.occupation.JobType; UpdateConnectedPlayersMessage.Send(); //fire all hooks var info = SpawnInfo.Player(occupation, characterSettings, CustomNetworkManager.Instance.humanPlayerPrefab, SpawnDestination.At(spawnPos), spawnItems: spawnItems); Spawn._ServerFireClientServerSpawnHooks(SpawnResult.Single(info, newPlayer)); return(newPlayer); }