A component wrapping a world object that Lua scripts can see and change. Holds a class name, map keyvalues, host-synced net variables and a tint that is applied to child model renderers.
using System.Collections.Generic;
using System.Linq;
namespace RoleplayFramework.Scripting;
/// <summary>
/// A world object Lua can see and control: map-placed (set <see cref="Class"/> and <see cref="KeyValues"/> in the
/// editor, and make the object networked) or created at runtime with <c>ents.Create</c>.
/// Class, NW vars and tint are host-written; transforms of networked objects replicate automatically.
/// </summary>
public sealed class LuaEntity : Component, INetVarHost
{
/// <summary>Entity class, e.g. "rp_door". Lua finds entities by class.</summary>
[Property, Sync( SyncFlags.FromHost )] public string Class { get; set; } = "prop";
/// <summary>Map-authored settings as "key=value;key2=value2" (e.g. "title=City Hall;price=100").</summary>
[Property] public string KeyValues { get; set; } = "";
[Sync( SyncFlags.FromHost )] public NetDictionary<string, string> NetVars { get; set; } = new();
[Sync( SyncFlags.FromHost )] public Color Tint { get; set; } = Color.White;
/// <summary>Created by client Lua (ClientsideModel): exists only on that client, which may change it.</summary>
public bool IsClientside { get; set; }
Color _appliedTint = Color.White;
public string GetKeyValue( string key )
{
foreach ( var part in (KeyValues ?? "").Split( ';' ) )
{
int eq = part.IndexOf( '=' );
if ( eq <= 0 ) continue;
if ( part.Substring( 0, eq ).Trim() == key ) return part.Substring( eq + 1 ).Trim();
}
return null;
}
protected override void OnUpdate()
{
if ( Tint == _appliedTint ) return;
_appliedTint = Tint;
foreach ( var r in Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) ) r.Tint = Tint;
}
public static IEnumerable<LuaEntity> All( Scene scene ) =>
scene is null ? Enumerable.Empty<LuaEntity>() : scene.GetAllComponents<LuaEntity>().Where( e => e.IsValid() );
}