Skip to content

Getting Script Classes

In AngelScript you can access Postal3Script attributes from one way to another, but you can also do the same thing with AngelScript classes.

However there are 3 downsides:

  • The script class must be cached, otherwise it won't work
  • Casting must be done manually, because AngelScript cannot do it automatically
  • The only way to detect if it's cached (or wrong) is to check if the script object is null or not

We'll use GetScriptObj for this.

Example: (from PC, modified)

class PCMonitor : IPostal3Script
{
    CP3SObj@ self;
    int iMaxSkins;
}

class PC : IPostal3Script
{
    // Dummy
    void Init(){}

    CP3SObj@ self;

    // This must be declared as a handle!
    PCMonitor@ monitor;

    PC(CP3SObj@ obj)
    {
        @self = @obj;

        // Get the closest monitor to us after everything's loaded
        engine.DelayedExecution(0, "PC", "GetMonitor", self);
    }

    void GetMonitor()
    {
        CP3SObj@ mon = null;

        array<CP3SObj@> aNPC = engine.GetArrayOfEntitiesRadius(self, 96);
        for (uint i = 0; i < aNPC.length(); i++)
        {
            if ( @aNPC[i] == null )
                continue;

            if ( @aNPC[i] == @self )
                continue;

            if ( aNPC[i].GetBaseEntity().GetClassName() != "cr_prop_interactable" )
                continue;

            if ( aNPC[i].GetManner() != "PCMonitor" )
                continue;

            // We got ourselves a monitor, break!
            @mon = @aNPC[i];
            break;
        }

        // Failed to get a monitor
        if (@mon == null)
            return;

        // We'll now attempt getting the script class to the monitor we got earlier
        @monitor = cast<PCMonitor@>(GetScriptObj("PCMonitor", mon));

        // Class wasn't cached for some reason! 
        // (but it's also generally a good idea to do null checking)
        if (@monitor == null)
            return;

        // We can now access the variables... like this
        Printf("Monitor Max Skins: %d\n", monitor.iMaxSkins);

        // even all of its handles
        if (@monitor.self != null)
            Printf("Monitor Faction: %s\n", monitor.self.GetFaction());
    }
}