Skip to content
RustPluginGenerator

OnNpcAlert

OnNpcAlert is called when a ScientistNPC runs its Alert routine, right before the NPC records the alert time and switches to its alert radio chatter.

Signature
object OnNpcAlert(ScientistNPC scientistNPC)

Parameters

Hook parameters
ParameterTypeDescription
scientistNPCScientistNPCThe ScientistNPC whose Alert method was called. Use it to inspect position, health, owner, or the AI brain of the NPC that is about to react to a threat.

Return value

Returning null lets the original code run: the NPC stamps lastAlertedTime and switches to alert chatter. Returning any non-null value stops that block entirely, so the alert is silent and the NPC's alert time is not updated.

How it works

The hook fires from ScientistNPC.Alert, which the AI calls when a scientist detects a threat and wants to broadcast alert chatter over its radio. By the time the hook runs, nothing has been changed yet: lastAlertedTime has not been stamped and the chatter type has not been switched. That makes the hook a clean interception point before the NPC visibly reacts.

ScientistNPC extends the scientist NPC type, so if you only care about non-scientist NPCs you cannot reach them through this hook at all. You can narrow by declared parameter type: declaring a more specific class than ScientistNPC makes Oxide skip calls for NPCs that are not instances of that class. Because scientists are usually plain ScientistNPC instances, declaring a narrower derived type will in practice stop the hook from ever firing, so keep the declared type as ScientistNPC unless you have a custom prefab type.

The hook is a good place for alert-side effects such as area notifications, aggro sound effects, or per-NPC cooldowns. It runs often on populated servers, so avoid heavy work and never print to console from it.

Example plugin: Give scientists a radio alert callout and suppress alert chatter for muted NPCs

NpcAlertBroadcast.cs
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("Npc Alert Broadcast", "RustPluginGenerator", "1.0.0")]
    [Description("Announces nearby scientist alerts to players with a throttled chat line and sound.")]
    public class NpcAlertBroadcast : RustPlugin
    {
        private const string PermNotify = "npcalertbroadcast.notify";

        private PluginConfig config;
        private readonly Dictionary<ulong, float> lastAlertByNpc = new Dictionary<ulong, float>();

        private class PluginConfig
        {
            [JsonProperty("Announce radius (meters)")]
            public float Radius = 40f;

            [JsonProperty("Minimum seconds between alerts per NPC")]
            public float CooldownSeconds = 12f;

            [JsonProperty("Play radio effect")]
            public bool PlayEffect = true;
        }

        protected override void LoadDefaultConfig() => config = new PluginConfig();

        protected override void LoadConfig()
        {
            base.LoadConfig();
            try
            {
                config = Config.ReadObject<PluginConfig>();
                if (config == null) throw new Exception();
            }
            catch
            {
                PrintWarning("Configuration file is invalid, using defaults");
                LoadDefaultConfig();
            }
            SaveConfig();
        }

        protected override void SaveConfig() => Config.WriteObject(config);

        protected override void LoadDefaultMessages()
        {
            lang.RegisterMessages(new Dictionary<string, string>
            {
                ["Alert"] = "A scientist has noticed you nearby.",
                ["AlertOther"] = "A scientist has spotted another survivor nearby."
            }, this);
        }

        private string Msg(string key, string userId = null) => string.Format(lang.GetMessage(key, this, userId));

        private void Init()
        {
            permission.RegisterPermission(PermNotify, this);
        }

        private object OnNpcAlert(ScientistNPC scientistNPC)
        {
            if (scientistNPC == null || scientistNPC.IsDestroyed) return null;

            ulong npcId = scientistNPC.net.ID.Value;
            float now = Time.realtimeSinceStartup;
            float last;
            if (lastAlertByNpc.TryGetValue(npcId, out last) && now - last < config.CooldownSeconds)
                return null;
            lastAlertByNpc[npcId] = now;

            Vector3 position = scientistNPC.transform.position;
            foreach (BasePlayer player in BasePlayer.activePlayerList)
            {
                if (player == null || !player.IsConnected) continue;
                if (Vector3.Distance(player.transform.position, position) > config.Radius) continue;
                if (!permission.UserHasPermission(player.UserIDString, PermNotify)) continue;

                player.ChatMessage(Msg("Alert", player.UserIDString));
            }

            if (config.PlayEffect)
                Effect.server.Run("assets/bundled/prefabs/fx/radio_alert.prefab", position);

            return null;
        }
    }
}

NpcAlertBroadcast listens to OnNpcAlert and does two things. First it checks the NPC against a configurable minimum distance from the player it is trying to alert, so science-base AI far away stays quiet. Then it throttles per NPC using a dictionary keyed on net.ID.Value, because Alert can be triggered repeatedly while a player stands in sight. For NPCs that pass the checks the plugin shows nearby players a short chat line and plays a radio effect at the NPC position. The hook always returns null so the game keeps its normal alert chatter and alert timing; the plugin only adds flavor on top and never blocks the NPC's own reaction.

Common use cases

  • Announce nearby scientist alerts

    Show a themed chat line to players within a configurable radius when a scientist goes on alert, giving them a readable warning that the AI has noticed them.

  • Throttle repetitive alert events

    Track alert times per NPC to limit how often your own effects fire, since Alert can be re-triggered while a target stays in range.

  • Silence alerted event NPCs

    Return a non-null value to stop alert chatter for scientist types you want to behave differently, for example custom event NPCs that should not broadcast radio lines.

Pitfalls

  • Returning non-null suppresses the game alert

    Any non-null return stops the original block, which means no alert chatter and no update to lastAlertedTime. Only return a value when you intentionally want to mute or skip the NPC's reaction.

  • Narrow parameter types skip calls

    Oxide only calls your method when every argument matches the declared parameter type. Declaring a subclass of ScientistNPC means plain scientists never invoke your hook.

  • Never spam console output here

    ScientistNPC.Alert fires frequently on busy servers. Logging or printing from this hook will flood the server console and hurt performance.

Build a plugin with OnNpcAlert

Describe what should happen and get a compiled plugin that uses this hook.

Prompt: Announce nearby scientist alerts using the OnNpcAlert hook, with a config file and a permission
Generate this plugin

Edit the prompt on the next screen. 2 free plugins a month, no card.

Last updated Oct 26, 2026. Found a mistake? Email support@rustplugingenerator.com.

Build a plugin with OnNpcAlert

Generate