Конечно, я постараюсь помочь вам найти ошибку. Пришлите исходный код, и я посмотрю, что можно сделать.
using Newtonsoft.Json;
using System.Collections.Generic;
using UnityEngine;
using Oxide.Core.Plugins;
using Oxide.Core;
using System.Linq;
namespace Oxide.Plugins
{
[Info("Meteorite", "walkinrey", "1.0.8")]
public class Meteorite : RustPlugin
{
[PluginReference] private Plugin MarkerManager;
private SphereEntity _radEnt;
private List<BaseEntity> _meteorEntities = new List<BaseEntity>();
private List<Vector3> _spawnPositions = new List<Vector3>();
private bool _eventActive = false;
private static string[] _shakePrefabs =
{
"assets/prefabs/weapons/bone knife/effects/strike_screenshake.prefab",
"assets/prefabs/weapons/hatchet/effects/strike_screenshake.prefab",
"assets/prefabs/weapons/pickaxe/effects/strike_screenshake.prefab",
"assets/prefabs/weapons/salvaged_axe/effects/strike_screenshake.prefab",
"assets/bundled/prefabs/fx/screen_jump.prefab"
};
#region Конфиг
private Configuration _config;
private class Configuration
{
[JsonProperty("Запуск ивента")] public EventStart starter = new EventStart();
public class EventStart
{
[JsonProperty("Запускать автоматически ивент?")] public bool autoStart = true;
[JsonProperty("Минимальное время до старта ивена")] public int minTime = 10800;
[JsonProperty("Максимальное время до старта ивента")] public int maxTime = 16800;
[JsonProperty("Минимальное количество игроков для запуска ивента")] public int minPlayers = 4;
[JsonProperty("Шанс, что метеорит обойдет остров стороной")] public int chance = 20;
}
[JsonProperty("Оповещения")] public Notifications notice = new Notifications();
public class Notifications
{
[JsonProperty("Выводить сообщение в чат о падающем метеорите?")] public bool needChatMessage = true;
[JsonProperty("Активировать тряску при приземлении метеорита?")] public bool needEarthquake = true;
}
[JsonProperty("Радиация")] public RadSettings radiation = new RadSettings();
public class RadSettings
{
[JsonProperty("Включить радиацию на месте метеорита?")] public bool needRadiation = true;
[JsonProperty("Радиус радиации")] public float radius = 10f;
[JsonProperty("Сила радиации")] public float strong = 5f;
}
[JsonProperty("Метеорит")] public MeteorSettings meteor = new MeteorSettings();
public class MeteorSettings
{
[JsonProperty("Радиус метеорита")] public float radius = 40f;
[JsonProperty("Количество падающих метеоритов")] public int rocketsAmount = 50;
[JsonProperty("Множитель урона от метеоритов")] public float damage = 3f;
[JsonProperty("Длительность падения метеоритов")] public int duration = 120;
[JsonProperty("Спавн предметов")] public ItemsSpawning itemsSpawn = new ItemsSpawning();
[JsonProperty("Спавн ученых")] public ScientistSpawning scientistSpawn = new ScientistSpawning();
[JsonProperty("Спавн каменных глыб")] public RocksSpawning rocksSpawn = new RocksSpawning();
[JsonProperty("Через сколько минут метеорит исчезнет")] public int meteorDespawn = 15;
public class MeteorItem
{
[JsonProperty("Shortname предмета")] public string shortname = "";
[JsonProperty("Количество предмета")] public MinMax amount = new MinMax();
}
public class MinMax
{
[JsonProperty("Минимум")] public int min = 1;
[JsonProperty("Максимум")] public int max = 2;
}
public class ScientistSpawning
{
[JsonProperty("Спавнить ученых?")] public bool spawnScientists = true;
[JsonProperty("Спавнить ученых после взрыва обычного метеорита?")] public bool spawnOnSimple = true;
[JsonProperty("Спавнить ученых после взрыва огненного метеорита?")] public bool spawnOnFire = false;
[JsonProperty("Шанс спавна ученых")] public int chance = 40;
[JsonProperty("Сколько ученых спавнить?")] public MinMax amount = new MinMax();
}
public class RocksSpawning
{
[JsonProperty("Спавнить каменные глыбы?")] public bool spawnRocks = true;
[JsonProperty("Спавнить глыбы после взрыва обычного метеорита?")] public bool spawnOnSimple = true;
[JsonProperty("Спавнить глыбы после взрыва огненного метеорита?")] public bool spawnOnFire = true;
[JsonProperty("Шанс спавна каменных глыб")] public int chance = 10;
[JsonProperty("Из каких камней будет состоять каменная глыба?")] public string[] rockPrefabs = {"assets/bundled/prefabs/autospawn/resource/ores/sulfur-ore.prefab", "assets/bundled/prefabs/autospawn/resource/ores/metal-ore.prefab", "assets/bundled/prefabs/autospawn/resource/ores/stone-ore.prefab"};
}
public class ItemsSpawning
{
[JsonProperty("Спавнить предметы у взорвавшегося метеорита?")] public bool spawnItems = true;
[JsonProperty("Сколько предметов будет спавниться?")] public MinMax amount = new MinMax {min = 1, max = 4};
[JsonProperty("Шанс спавна предметов")] public int chance = 50;
[JsonProperty("Предметы, которые будут спавниться у взорвавшегося метеорита")] public List<MeteorItem> items = new List<MeteorItem>();
}
}
[JsonProperty("Маркер")] public MarkerSettings marker = new MarkerSettings();
public class MarkerSettings
{
[JsonProperty("Отображать маркер с местонахождением метеорита на карте?")] public bool needMarker = false;
[JsonProperty("Отображаемое название")] public string displayName = "Метеорит";
[JsonProperty("Основной цвет маркера (без #)")] public string mainColor = "F39C12";
[JsonProperty("Цвет обводки маркера (без #)")] public string outlineColor = "F39C12";
}
public static Configuration GetDefaultConfiguration()
{
Configuration _config = new Configuration();
_config.meteor.itemsSpawn.items.Add(new Configuration.MeteorSettings.MeteorItem
{
shortname = "sulfur.ore",
amount = new Configuration.MeteorSettings.MinMax
{
min = 50,
max = 200
}
});
_config.meteor.itemsSpawn.items.Add(new Configuration.MeteorSettings.MeteorItem
{
shortname = "metal.ore",
amount = new Configuration.MeteorSettings.MinMax
{
min = 100,
max = 500
}
});
_config.meteor.itemsSpawn.items.Add(new Configuration.MeteorSettings.MeteorItem
{
shortname = "stones",
amount = new Configuration.MeteorSettings.MinMax
{
min = 100,
max = 500
}
});
_config.meteor.itemsSpawn.items.Add(new Configuration.MeteorSettings.MeteorItem
{
shortname = "hq.metal.ore",
amount = new Configuration.MeteorSettings.MinMax
{
min = 10,
max = 30
}
});
return _config;
}
}
protected override void LoadDefaultConfig() => _config = Configuration.GetDefaultConfiguration();
protected override void SaveConfig() => Config.WriteObject(_config);
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>();
if (_config == null) LoadDefaultConfig();
}
catch
{
LoadDefaultConfig();
}
NextTick(SaveConfig);
}
#endregion
#region Локализация
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["MeteoriteComing"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nНа радарах был обнаружен двигающийся в сторону острова метеорит, будьте на готове!",
["MeteoriteFail"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nМетеорит обошел остров стороной.",
["MeteoriteInAtmosphere"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nМетеорит вошел в атмосферу!",
["MeteorCrash"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nДо столкновения %SECONDS% секунд...",
["MeteorCrashed"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nМетеорит столкнулся с землей и приземлился! Его местоположение отмечено на карте оранжевым кругом.",
["MeteorDespawning"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nМетеорит распадется под действием кислорода через %MINUTES% минут.",
["MeteorDespawned"] = "<size=16>[<color=blue>Ученые Cobalt</color>]</size>\nМетеорит окончательно распался под действием кислорода.",
["EventIsActive"] = "<size=16>[Метеорит]</size>\nВы не можете вызвать метеорит, потому что ивент уже активен!",
["PlayerNotFinded"] = "<size=16>[Метеорит]</size>\nИгрок не найден!",
["MeteorCalledPlayer"] = "<size=16>[Метеорит]</size>\nВы успешно вызвали метеорит на позицию игрока %NAME%",
["MeteorCalled"] = "<size=16>[Метеорит]</size>\nВы успешно вызвали метеорит!",
["EventNotActive"] = "<size=16>[Метеорит]</size>\nИвент не активен!",
["EventStopped"] = "<size=16>[Метеорит]</size>\nВы успешно остановили ивент!",
["NoPermission"] = "<size=16>[Метеорит]</size>\nУ вас нет разрешения на использование этой команды!",
["NotEnoughPlayers"] = "Недостаточно игроков для начала ивента!",
["CommandsInfo"] = "<size=16>[Метеорит]</size>\n/meteor random - вызывает метеорит на рандомной точке\n/meteor player {STEAMID} - вызывает метеорит на позиции игрока\n/meteor stop - останавливает запущенный ивент (плагин будет перезагружен)"
}, this, "ru");
lang.RegisterMessages(new Dictionary<string, string>
{
["MeteoriteComing"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nA meteorite has been detected on radar heading toward the island, stand by!",
["MeteoriteFail"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nThe meteorite bypassed the island.",
["MeteoriteInAtmosphere"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nA meteorite has entered the atmosphere!",
["MeteorCrash"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nBefore the collision %SECONDS% seconds...",
["MeteorCrashed"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nA meteorite collided with the ground and landed! It's location is marked on the map with an orange circle.",
["MeteorDespawning"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nThe meteorite will disintegrate due to oxygen in %MINUTES% minutes.",
["MeteorDespawned"] = "<size=16>[<color=blue>Cobalt Scientists</color>]</size>\nThe meteorite finally disintegrated under the influence of oxygen.",
["EventIsActive"] = "<size=16>[Meteorite]</size>\nYou can't call meteorite because event is active!",
["PlayerNotFinded"] = "<size=16>[Meteorite]</size>\nPlayer not finded!",
["MeteorCalled"] = "<size=16>[Meteorite]</size>\nYou successfully called a meteorite!",
["MeteorCalledPlayer"] = "<size=16>[Meteorite]</size>\nYou successfully called a meteorite on %NAME% position!",
["EventNotActive"] = "<size=16>[Meteorite]</size>\nEvent is not active!",
["NoPermission"] = "<size=16>[Meteorite]</size>\nYou don't have permission to use this command!",
["EventStopped"] = "<size=16>[Meteorite]</size>\nYou successfully stopped the event!",
["NotEnoughPlayers"] = "Not enough players to start event!",
["CommandsInfo"] = "<size=16>[Meteorite]</size>\n/meteor random - calling meteorite on random point\n/meteor player {STEAMID} - calling meteorite on player position\n/meteor stop - stopping launched event (plugin will be reloaded)"
}, this, "en");
}
#endregion
#region Методы
[ConsoleCommand("meteor")]
private void cnslCommand(ConsoleSystem.Arg arg)
{
if(arg.Player() != null)
{
var player = arg.Player();
if(!permission.UserHasPermission(player.UserIDString, "meteorite.admin"))
{
player.ConsoleMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
if(!arg.HasArgs())
{
player.ConsoleMessage(lang.GetMessage("CommandsInfo", this, player.UserIDString));
return;
}
switch(arg.Args[0])
{
case "random":
if(_eventActive)
{
player.ConsoleMessage(lang.GetMessage("EventIsActive", this, player.UserIDString));
return;
}
if(BasePlayer.activePlayerList.Count < _config.starter.minPlayers)
{
player.ConsoleMessage(lang.GetMessage("NotEnoughPlayers", this, player.UserIDString));
return;
}
StartEvent();
player.ConsoleMessage(lang.GetMessage("MeteorCalled", this, player.UserIDString));
return;
case "player":
if(_eventActive)
{
player.ConsoleMessage(lang.GetMessage("EventIsActive", this, player.UserIDString));
return;
}
if(BasePlayer.activePlayerList.Count < _config.starter.minPlayers)
{
player.ConsoleMessage(lang.GetMessage("NotEnoughPlayers", this, player.UserIDString));
return;
}
BasePlayer attackPlayer = BasePlayer.Find(arg.Args[1]);
if(attackPlayer == null)
{
player.ConsoleMessage(lang.GetMessage("PlayerNotFinded", this, player.UserIDString));
return;
}
StartEvent(attackPlayer.GetNetworkPosition());
player.ConsoleMessage(lang.GetMessage("MeteorCalledPlayer", this, player.UserIDString).Replace("%NAME%", attackPlayer.ToString()));
return;
case "stop":
if(!_eventActive)
{
player.ConsoleMessage(lang.GetMessage("EventNotActive", this, player.UserIDString));
return;
}
player.ConsoleMessage(lang.GetMessage("EventStopped", this, player.UserIDString));
DespawnMeteor();
return;
}
return;
}
if(!arg.HasArgs())
{
PrintWarning(lang.GetMessage("CommandsInfo", this));
return;
}
switch(arg.Args[0])
{
case "random":
if(_eventActive)
{
PrintError(lang.GetMessage("EventIsActive", this));
return;
}
if(BasePlayer.activePlayerList.Count < _config.starter.minPlayers)
{
PrintError(lang.GetMessage("NotEnoughPlayers", this));
return;
}
StartEvent();
Puts(lang.GetMessage("MeteorCalled", this));
return;
case "player":
if(_eventActive)
{
PrintError(lang.GetMessage("EventIsActive", this));
return;
}
if(BasePlayer.activePlayerList.Count < _config.starter.minPlayers)
{
PrintError(lang.GetMessage("NotEnoughPlayers", this));
return;
}
BasePlayer attackPlayer = BasePlayer.Find(arg.Args[1]);
if(attackPlayer == null)
{
PrintError(lang.GetMessage("PlayerNotFinded", this));
return;
}
StartEvent(attackPlayer.GetNetworkPosition());
Puts(lang.GetMessage("MeteorCalledPlayer", this).Replace("%NAME%", attackPlayer.displayName));
return;
case "stop":
if(!_eventActive)
{
PrintError(lang.GetMessage("EventNotActive", this));
return;
}
Puts(lang.GetMessage("EventStopped", this));
NextTick(() => Interface.Oxide.ReloadPlugin(Title));
return;
}
}
private void StartEvent(Vector3 mtPos = new Vector3())
{
if(_eventActive) return;
if(BasePlayer.activePlayerList.Count < _config.starter.minPlayers)
{
PrintWarning(lang.GetMessage("NotEnoughPlayers", this));
return;
}
_eventActive = true;
SendMessageToAll("MeteoriteComing");
timer.Once(30f, () =>
{
if(UnityEngine.Random.Range(0, 100) < _config.starter.chance)
{
SendMessageToAll("MeteoriteFail");
_eventActive = false;
}
else
{
SendMessageToAll("MeteoriteInAtmosphere");
timer.Once(5f, () =>
{
int secondsLeft = 6;
timer.Repeat(1f, 5, () =>
{
secondsLeft--;
SendMessageToAll("MeteorCrash", new MessageArgs
{
keyWord = "%SECONDS%",
usingWord = secondsLeft.ToString()
});
if(secondsLeft <= 1)
{
if(_config.notice.needEarthquake) BasePlayer.activePlayerList.ToList().ForEach(x => ScreenShake(x));
var meteorPos = GetEventPosition();
if(mtPos != new Vector3()) meteorPos = mtPos;
if(_config.radiation.needRadiation)
{
TriggerRadiation radiation = null;
SphereEntity outerSphere = (SphereEntity)GameManager.server.CreateEntity("assets/prefabs/visualization/sphere.prefab", meteorPos, Quaternion.identity, true);
outerSphere.currentRadius = (_config.radiation.radius * 10) + 50;
outerSphere.lerpSpeed = 0;
outerSphere.enableSaving = false;
outerSphere.Spawn();
SphereCollider outerCollider = outerSphere.gameObject.AddComponent<SphereCollider>();
outerCollider.isTrigger = true;
outerCollider.radius = 0.5f;
radiation = outerSphere.gameObject.AddComponent<TriggerRadiation>();
radiation.RadiationAmountOverride = _config.radiation.strong;
radiation.interestLayers = 131072;
radiation.enabled = true;
_radEnt = outerSphere;
}
SetMarker(meteorPos);
CallMeteor(meteorPos);
timer.Once(3f, () =>
{
SendMessageToAll("MeteorCrashed");
});
timer.Once(_config.meteor.meteorDespawn * 60 / 2, () =>
{
SendMessageToAll("MeteorDespawning", new MessageArgs {keyWord = "%MINUTES%", usingWord = _config.meteor.meteorDespawn.ToString()});
});
timer.Once(_config.meteor.meteorDespawn * 60, DespawnMeteor);
}
});
});
}
});
}
private void DespawnMeteor()
{
foreach(var ent in _meteorEntities)
{
if(ent == null) continue;
ent.Kill();
}
if(_radEnt != null) _radEnt.Kill();
if(_eventActive) SendMessageToAll("MeteorDespawned");
DeleteMarker();
_eventActive = false;
}
private void CallMeteor(Vector3 pos)
{
int duration = _config.meteor.duration;
int rocketsAmount = _config.meteor.rocketsAmount;
float intervals = duration / rocketsAmount;
timer.Repeat(intervals, rocketsAmount, () =>
{
SpawnRocket(pos, _config.meteor.radius);
});
}
private void GetSpawnPositions()
{
if(_spawnPositions.Count >= 5) return;
for(int i = 0; i < 500; i++)
{
Vector3 randomPos = GetPosition();
randomPos.y = TerrainMeta.HeightMap.GetHeight(randomPos);
if(randomPos.y == 0) continue;
if(_spawnPositions.Count != 0)
{
if(_spawnPositions.Where(x => Vector3.Distance(x, randomPos) < 50)?.Count() != 0) // Проверяем, находятся ли рядом другие точки спавна
{
continue;
}
}
if(Physics.OverlapSphere(randomPos, 2f, LayerMask.GetMask("Water")).Length != 0) continue; // Проверяем, находится ли точка спавна в воде
List<BaseEntity> visEntities = new List<BaseEntity>();
Vis.Entities(randomPos, 100f, visEntities, LayerMask.GetMask("Default", "Construction", "World", "Deployed", "Trigger", "Prevent Building", "Water"));
if(visEntities.Count != 0)
{
if(visEntities.Where(x => x is BuildingPrivlidge)?.Count() != 0) continue; // Проверяем, находятся ли шкафы в точке спавна
}
_spawnPositions.Add(randomPos);
}
if(_spawnPositions.Count <= 0)
{
GetSpawnPositions();
return;
}
Puts($"{_spawnPositions.Count} точек для спавна ивента найдено!");
}
#endregion
#region Хуки
private object OnMeteorEntity(BaseEntity entity)
{
if(!_meteorEntities.Contains(entity)) _meteorEntities.Add(entity);
return null;
}
private void Loaded() => permission.RegisterPermission("meteorite.admin", this);
private void OnServerInitialized()
{
if(_config.marker.needMarker && MarkerManager == null)
{
PrintError("Вы включили отображение маркера на карте, но вспомогательный плагин MarkerManager by Orange у вас не установлен. Пожалуйста, установите его с umod.org");
NextTick(() =>
{
Interface.Oxide.UnloadPlugin(Title);
return;
});
}
if(_config.starter.autoStart)
{
timer.Every(UnityEngine.Random.Range(_config.starter.minTime, _config.starter.maxTime), () => StartEvent());
}
GetSpawnPositions();
}
private void Unload() => DespawnMeteor();
#endregion
#region Хелперы
private void SetMarker(Vector3 pos)
{
if(!_config.marker.needMarker) return;
if(MarkerManager == null)
{
PrintError("Вы включили поддержку MarkerManager, но сам плагин у вас не установлен!");
return;
}
DeleteMarker();
MarkerManager.CallHook("API_CreateMarker", pos, "Meteor", 0, 3f, _config.meteor.radius / 100f, _config.marker.displayName, _config.marker.mainColor, _config.marker.outlineColor);
}
private void DeleteMarker()
{
if(!_config.marker.needMarker) return;
if(MarkerManager == null) return;
MarkerManager.CallHook("API_RemoveMarker", "Meteor");
}
private static Vector3 GetPosition()
{
float mapsize = (TerrainMeta.Size.x / 2) - 600f;
return new Vector3(UnityEngine.Random.Range(-mapsize, mapsize), 0f, UnityEngine.Random.Range(-mapsize, mapsize));
}
private Vector3 GetEventPosition() => _spawnPositions.GetRandom();
private void ScreenShake(BasePlayer player)
{
timer.Repeat(0.2f, 15, () =>
{
string screenPrefab = _shakePrefabs[UnityEngine.Random.Range(0, _shakePrefabs.Length)];
Effect.server.Run(screenPrefab, player.transform.position);
});
}
private void SpawnRocket(Vector3 origin, float radius)
{
ItemDefinition projectileItem = null;
bool isRocket = false;
if(UnityEngine.Random.Range(0, 100) < 30)
{
projectileItem = ItemManager.FindItemDefinition("ammo.rocket.fire");
isRocket = true;
}
else projectileItem = ItemManager.FindItemDefinition("ammo.rocket.hv");
ItemModProjectile component = projectileItem.GetComponent<ItemModProjectile>();
Vector3 launchPos = origin + new Vector3(UnityEngine.Random.insideUnitCircle.x + 2f * radius, 0, UnityEngine.Random.insideUnitCircle.y * radius) - (Vector3.up * -2f + Vector3.right).normalized * 200f;
launchPos = new Vector3(launchPos.x + UnityEngine.Random.Range(-50, 50), launchPos.y, launchPos.z);
BaseEntity entity = GameManager.server.CreateEntity(component.projectileObject.resourcePath, launchPos, Quaternion.identity, true);
TimedExplosive timedExplosive = entity.GetComponent<TimedExplosive>();
ServerProjectile serverProjectile = entity.GetComponent<ServerProjectile>();
timedExplosive.SetDamageScale(_config.meteor.damage);
serverProjectile.gravityModifier = 1f;
serverProjectile.speed = 20f;
timedExplosive.timerAmountMin = 300;
timedExplosive.timerAmountMax = 300;
entity.SendMessage("InitializeVelocity", (object)((Vector3.up * -2f + Vector3.right).normalized * 1f));
MeteorRocket rocket = entity.gameObject.AddComponent<MeteorRocket>();
if(isRocket) rocket.type = MeteorRocket.RocketType.Rocket;
else rocket.type = MeteorRocket.RocketType.Standard;
rocket.spawnScientists = _config.meteor.scientistSpawn;
rocket.spawnRocks = _config.meteor.rocksSpawn;
rocket.spawnItems = _config.meteor.itemsSpawn;
entity.Spawn();
}
private void SendMessageToAll(string msgKey, MessageArgs args = null)
{
if(!_config.notice.needChatMessage) return;
foreach(var player in BasePlayer.activePlayerList)
{
string msg = lang.GetMessage(msgKey, this, player.UserIDString);
if(args != null) msg = msg.Replace(args.keyWord, args.usingWord);
SendReply(player, msg);
}
}
#endregion
#region Дополнительные классы
private class MessageArgs
{
public string keyWord, usingWord;
}
private class MeteorRocket : MonoBehaviour
{
public enum RocketType {Standard, Rocket};
public RocketType type;
public Configuration.MeteorSettings.ScientistSpawning spawnScientists;
public Configuration.MeteorSettings.RocksSpawning spawnRocks;
public Configuration.MeteorSettings.ItemsSpawning spawnItems;
private void SpawnBot(Vector3 position)
{
BaseEntity entity = GameManager.server.CreateEntity("assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_full_any.prefab", position, Quaternion.identity);
entity.Spawn();
BaseNavigator navigator = entity.GetComponent<BaseNavigator>();
navigator.MaxRoamDistanceFromHome = navigator.BestMovementPointMaxDistance = navigator.BestRoamPointMaxDistance = 20f * 0.85f;
navigator.DefaultArea = "Walkable";
navigator.Agent.agentTypeID = -1372625422;
navigator.MaxWaterDepth = 0.5f;
navigator.CanUseNavMesh = true;
navigator.CanUseAStar = true;
navigator.Init(entity as BaseCombatEntity, navigator.Agent);
navigator.PlaceOnNavMesh();
var brain = entity.GetComponent<ScientistNPC>().Brain;
brain.Invoke(() =>
{
brain.ForceSetAge(0);
brain.Pet = false;
brain.UseAIDesign = true;
brain.AllowedToSleep = false;
brain._baseEntity = entity.GetComponent<HumanNPC>();
brain.HostileTargetsOnly = false;
brain.MaxGroupSize = 0;
brain.Senses.Init(owner: entity, memoryDuration: 5f, range: 30f, targetLostRange: 30f * 2f, visionCone: -1f, checkVision: true,
checkLOS: true, ignoreNonVisionSneakers: true, listenRange: 15f, hostileTargetsOnly: false, senseFriendlies: false,
ignoreSafeZonePlayers: false, senseTypes: EntityType.Player, refreshKnownLOS: true);
}, 0.1f);
Interface.Oxide.CallHook("OnMeteorEntity", entity);
}
private void OnDestroy()
{
if(spawnScientists.spawnScientists)
{
int scientistAmount = UnityEngine.Random.Range(spawnScientists.amount.min, spawnScientists.amount.max);
if(spawnScientists.spawnOnSimple && type == RocketType.Standard && UnityEngine.Random.Range(0,100) < spawnScientists.chance)
{
for(int i = 0; i < scientistAmount; i++)
{
int spawnSide = UnityEngine.Random.Range(0, 1);
if(spawnSide == 1)
{
SpawnBot(new Vector3(gameObject.transform.position.x + 5f, gameObject.transform.position.y, gameObject.transform.position.z + 5f));
}
else
{
SpawnBot(new Vector3(gameObject.transform.position.x + 5f * -1, gameObject.transform.position.y, gameObject.transform.position.z + 5f * -1));
}
}
}
if(spawnScientists.spawnOnFire && type == RocketType.Rocket && UnityEngine.Random.Range(0,100) < spawnScientists.chance)
{
for(int i = 0; i < scientistAmount; i++)
{
int spawnSide = UnityEngine.Random.Range(0, 1);
if(spawnSide == 1)
{
SpawnBot(new Vector3(gameObject.transform.position.x + 5f, gameObject.transform.position.y, gameObject.transform.position.z + 5f));
}
else
{
SpawnBot(new Vector3(gameObject.transform.position.x + 5f * -1, gameObject.transform.position.y, gameObject.transform.position.z + 5f * -1));
}
}
}
}
if(spawnRocks.spawnRocks)
{
if(spawnRocks.spawnOnSimple && type == RocketType.Standard && UnityEngine.Random.Range(0,100) < spawnRocks.chance)
{
BaseEntity entityFirst = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], gameObject.transform.position, Quaternion.identity);
entityFirst.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entityFirst);
BaseEntity entitySecond = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], new Vector3(gameObject.transform.position.x + 1f * 1, gameObject.transform.position.y, gameObject.transform.position.z + 1f * -1), Quaternion.identity);
entitySecond.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entitySecond);
BaseEntity entityThird = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], new Vector3(gameObject.transform.position.x + 1f * -1, gameObject.transform.position.y, gameObject.transform.position.z + 1f * -1), Quaternion.identity);
entityThird.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entityThird);
BaseEntity entityFour = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + 1f, gameObject.transform.position.z), Quaternion.identity);
entityFour.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entityFour);
}
if(spawnRocks.spawnOnFire && type == RocketType.Rocket && UnityEngine.Random.Range(0,100) < spawnRocks.chance)
{
BaseEntity entityFirst = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], gameObject.transform.position, Quaternion.identity);
entityFirst.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entityFirst);
BaseEntity entitySecond = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], new Vector3(gameObject.transform.position.x + 1f * 1, gameObject.transform.position.y, gameObject.transform.position.z + 1f * -1), Quaternion.identity);
entitySecond.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entitySecond);
BaseEntity entityThird = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], new Vector3(gameObject.transform.position.x + 1f * -1, gameObject.transform.position.y, gameObject.transform.position.z + 1f * -1), Quaternion.identity);
entityThird.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entityThird);
BaseEntity entityFour = GameManager.server.CreateEntity(spawnRocks.rockPrefabs[UnityEngine.Random.Range(0, spawnRocks.rockPrefabs.Length)], new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + 1f, gameObject.transform.position.z), Quaternion.identity);
entityFour.Spawn();
Interface.Oxide.CallHook("OnMeteorEntity", entityFour);
}
}
if(spawnItems.spawnItems && UnityEngine.Random.Range(0, 100) < spawnRocks.chance)
{
for(int i = 0; i < UnityEngine.Random.Range(spawnItems.amount.min, spawnItems.amount.max); i++)
{
var itemInfo = spawnItems.items[UnityEngine.Random.Range(0, spawnItems.items.Count)];
Item item = ItemManager.CreateByName(itemInfo.shortname, UnityEngine.Random.Range(itemInfo.amount.min, itemInfo.amount.max));
Interface.Oxide.CallHook("OnMeteorEntity", item.Drop(gameObject.transform.position, new Vector3()));
}
}
}
}
#endregion
}
}