OnEntityKill
OnEntityKill is called from BaseNetworkable.Kill before the entity is flagged destroyed and removed from the world. Returning a non-null value cancels the kill entirely.
object OnEntityKill(BaseNetworkable entity)Parameters
| Parameter | Type | Description |
|---|---|---|
entity | BaseNetworkable | The BaseNetworkable instance that is being killed, or has already been marked destroyed. Cast it to a more specific type (BasePlayer, BuildingBlock, StorageContainer, LootableCorpse) to inspect the entity that triggered the hook. |
Return value
Return null to let the kill proceed normally. Return any non-null value to cancel the kill: the original method exits before destroying the entity, so the object remains in the world.
How it works
The hook fires inside BaseNetworkable.Kill, before the engine increments its kill counter and destroys the object. It is used for every networked entity: players, building blocks, deployables, dropped items, corpses, vehicles and NPCs. Because the injection is at the top of Kill, entity.IsDestroyed is still false when your method runs, so you can safely read OwnerID, ShortPrefabName, position and any type-specific state. Declaring the parameter as a specific subclass such as BuildingBlock or BasePlayer makes Oxide skip the call whenever the entity is a different type, which is the cheapest way to scope the hook. Returning any non-null object stops the original kill path: the entity survives and stays in the world. This is a powerful but sharp tool, so prefer returning null for entities you do not handle. Do not run heavy work here, since large bases being wiped can fire the hook thousands of times in a single frame.
Example plugin: Protect building blocks during a raid grace window
using UnityEngine;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Oxide.Core;
namespace Oxide.Plugins
{
[Info("Raid Protected Kill", "RustPluginGenerator", "1.0.0")]
[Description("Blocks building block destruction during an admin-controlled raid protection window.")]
public class RaidProtectedKill : RustPlugin
{
private class PluginConfig
{
[JsonProperty("Protection duration (minutes)")]
public int DurationMinutes = 30;
[JsonProperty("Required permission")]
public string Permission = "raidprotectedkill.use";
}
private PluginConfig config;
private DateTime protectionEndsUtc = DateTime.MinValue;
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>
{
["Started"] = "Raid protection is now active for {0} minutes.",
["NotPermitted"] = "You do not have permission to use this command."
}, this);
}
private string Msg(string key, string userId = null, params object[] args) => string.Format(lang.GetMessage(key, this, userId), args);
private void Init()
{
permission.RegisterPermission(config.Permission, this);
}
[ConsoleCommand("raidprotectedkill.start")]
private void CmdStart(ConsoleSystem.Arg arg)
{
var player = arg.Player();
if (player != null && !permission.UserHasPermission(player.UserIDString, config.Permission))
{
SendReply(player, Msg("NotPermitted", player.UserIDString));
return;
}
protectionEndsUtc = DateTime.UtcNow.AddMinutes(config.DurationMinutes);
Server.Broadcast(Msg("Started", null, config.DurationMinutes));
Puts($"Raid protection active until {protectionEndsUtc:u}");
}
private object OnEntityKill(BuildingBlock block)
{
if (block == null || block.IsDestroyed) return null;
if (DateTime.UtcNow >= protectionEndsUtc) return null;
return true;
}
}
}The plugin uses OnEntityKill to block the destruction of BuildingBlock entities for a configurable number of minutes after a raid starts. An admin command raidprotect.start records a start time, and OnEntityKill returns a non-null sentinel while the window is open and the entity is a wall or foundation. Entities of any other type fall through and are killed normally. When the timer expires the hook returns null again. Config holds the protection duration and the required admin flag, and the remaining time is broadcast to chat when the window opens.
Common use cases
Cancel despawn of player-owned items
Return a non-null value for
DroppedItemorLootableCorpseinstances whoseOwnerIDmatches a tracked player so their belongings never vanish on server cleanup.Audit base wipes
Record the
ShortPrefabName, position andOwnerIDof everyBuildingBlockthat is killed so admins can review which structures were destroyed and when.Cancel NPC team kills
Prevent friendly
ScientistNPCinstances from being killed by teammates by returning a non-null value whenOwnerIDbelongs to a protected team.
Pitfalls
Fires for every despawn
Server cleanup, plugin calls to
Kill()and player wipes all route through this hook. Restrict to specific types with the parameter type to avoid running logic on unrelated entities.Returning non-null leaks entities
If you cancel the kill and never schedule a retry, the entity stays alive indefinitely. Track it and call
Kill()later once protection expires.Runs during mass wipes
A plugin calling
Kill()on hundreds of entities in a loop triggers the hook each time. Keep body code O(1) and avoid chat output or disk writes here.
Plugin recipes that use OnEntityKill
- How to make a Rust car spawn plugin (Oxide/Carbon)Adds a /car command that spawns a modular car with configured modules in front of the player, enforcing a permission, a spawn cooldown and a strict one-car-per-player limit. It tracks spawned cars through OnEntityKill so a player can get a new car only after the old one is destroyed.
- How to make a Rust crate loot lock plugin (first opener claims it)This plugin gives the first player who opens a loot container a temporary claim on it, enforced through the CanLootEntity hook, so anyone outside their team is blocked until the lock expires.
- How to make a Rust deployable limits plugin (per-prefab caps with VIP tiers)Caps how many of each deployable (by short prefab name) a player can own, with per-permission-group limits, using OnEntityBuilt to enforce, CanBuild to block placement early, and OnEntityKill plus a startup scan of BaseNetworkable.serverEntities to keep counts accurate.
- How to make a Rust horse spawn plugin (Oxide/Carbon cooldown)Adds a /horse command that spawns a ridable horse beside the player, tracks one horse per player, removes that player's previous horse and enforces a permission-gated cooldown. It uses OnEntityKill to forget horses that were destroyed by other means.
- How to make a Rust locked crate event plugin (timed monument drops)Spawns a hackable locked crate at a random configured monument on a repeating timer, announces the monument in chat, and removes the previous event crate before each new one. Uses OnServerInitialized, OnCrateHack, OnEntityKill and OnServerShutdown with a repeating Oxide timer.
- How to make a Rust NPC loot lock plugin (owner + team only)Locks NPC corpses to the killer and their team for a configurable number of seconds after death, then opens them to everyone. Uses OnEntityDeath to record ownership and CanLootEntity to gate looting.
- How to make a Rust offline raid protection plugin (cupboard based)Scales damage to building blocks and deployables when every player authorized on the covering tool cupboard has been offline for a configurable delay. Uses OnEntityTakeDamage and OnPlayerDisconnected, with a repeating timer that turns protection on and off.
- How to make a Rust sleeping bag cooldown plugin (Oxide/Carbon)Overrides the respawn cooldown on sleeping bags and beds to a fixed number of seconds, with a separate shorter cooldown for a VIP permission. Uses OnEntitySpawned, OnPlayerRespawned and a startup sweep in OnServerInitialized.
- How to make a Rust sleeping bag teleport plugin (bag list, warmup, cooldown)Adds /bag, which lists the player's sleeping bags, beds and beach towels with grid references, and /bag <number> to teleport to one after a warmup timer with a per-player cooldown. It relies on the OnEntitySpawned and OnEntityKill hooks to keep an index of placed spawn points.
- How to make a Rust vehicle limit plugin (per player, per type)Caps how many vehicles each player can own per vehicle type, blocking purchases and entity spawns once the limit is reached and allowing higher caps through permissions. It uses OnEntitySpawned and OnEntityKill to count and track vehicles.
- How to make a Rust vehicle owner lock plugin (team sharing)Adds per-vehicle ownership: a player can claim a vehicle with /claim, and only the owner and their team members can mount it. Ownership is enforced in the CanMountEntity hook and handed out when a vehicle is deployed.
- How to make a Rust vehicle spawn command plugin (owner-locked)Adds /mini, /scrapheli and /rowboat chat commands that spawn a vehicle in front of the player, with a permission per vehicle, a per-type active limit, cooldowns and OwnerID set on the spawned entity. It uses OnEntityKill to free the player's slot when their vehicle is destroyed.
Build a plugin with OnEntityKill
Describe what should happen and get a compiled plugin that uses this hook.
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 OnEntityKill
Generate