Scripting Examples

From Soldat2 Wiki
Revision as of 11:48, 10 June 2023 by Nerf cardboard (talk | contribs) (move to Category:Modding)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This page contains a selection of unofficial scripts to demonstrate the usage of various aspects of Soldat 2's scripting API.

Team Balancer

// a basic team-balancing script to illustrate how to implement simple
// chat-commands using S2 scripting

// 'using' directives let you omit namespacing
// eg: Player rather than the full Teal.Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Teal;

[DisallowMultipleComponent]

// the class name as defined here is what you need to refer to in any json
// config files, NOT the name of this script file. Case sensitive.
public class Balance : MonoBehaviour
{
    // called when the script is loaded
    private void Awake()
    {
        // this registers a function (OnPlayerChat in this case) to be called
        // whenever a player chat event occurs
        // for other types of events, check in the modding channel on S2 discord
        GameChat.instance.OnChat.AddListener(OnPlayerChat);
    }

    // called before the script is unloaded, probably when the server closes/restarts
    private void OnDestroy()
    {
        // presumably important to prevent your script from continuing to respond
        // to events after it gets removed/disabled
        GameChat.instance.OnChat.RemoveListener(OnPlayerChat);
    }

    // user-defined function for handling chat events - the name can be any
    // (valid) identifier, only the signature is important
    void OnPlayerChat(Player p, string msg)
    {
        // we are only implementing a single command in this example, but if
        // you want to have multiple commands a switch/case statement is probably
        // more appropriate
        if( msg == "!bal" || msg == "!balance" )
        {
            // first we grab a list of the players on each team
            List<Player> t0 = MonoSingleton<Players>.Get.GetPlayersOfTeam(0);
            List<Player> t1 = MonoSingleton<Players>.Get.GetPlayersOfTeam(1);

            // integer division rounds down, so we will only do something if teams
            // are unbalanced by more than one player
            int hdiff = (t0.Count-t1.Count)/2;
            if( hdiff > 0 )
            { // more players on team 0, move half the difference to team 1
                for( int i=0; i<hdiff; i++ ) t0[i].props["team"] = 1;
                return;
            }
            else if( hdiff < 0 )
            { // more players on team 1, move half the difference to team 0
                for( int i=0; i<-hdiff; i++ ) t1[i].props["team"] = 0;
                return;
            }
        }
    }

}