Skip to content

JFHeim/JFUtils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JF Utils

Adds some usefull utils for programmers.
Includes ServerSync.dll inside.
If you have any questions or suggestions please message me in discord: justafrogger

Merging the DLLs into your mod

Download the JFUtils.dll and the ServerSync.dll from the release section to the right. Including the DLLs is best done via ILRepack (https://github.com/ravibpatel/ILRepack.Lib.MSBuild.Task). You can load this package (ILRepack.Lib.MSBuild.Task) from NuGet.

If you have installed ILRepack via NuGet, simply create a file named ILRepack.targets in your project and copy the following content into the file

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="ILRepacker" AfterTargets="Build">
        <ItemGroup>
            <InputAssemblies Include="$(TargetPath)"/>
            <InputAssemblies Include="$(OutputPath)\JFUtils.dll"/>
        </ItemGroup>
        <ILRepack Parallel="true" DebugInfo="true" Internalize="true" InputAssemblies="@(InputAssemblies)"
                  OutputFile="$(TargetPath)" TargetKind="SameAsPrimaryAssembly" LibraryPath="$(OutputPath)"/>
    </Target>
</Project>

Make sure to set the JFUtils.dll in your project to "Copy to output directory" in the properties of the DLLs and to add a reference to it.

Documentation

ModBase

All methods, fields and properties are static.

Methods

CreateMod

void CreateMod(BaseUnityPlugin _plugin, string modName, string modAuthor, string modVersion, bool pathAll = true)
Allows you to create your own mod automatically. Call ModBase.CreateMod() to create a mod. It will automatically:

  • create ConfigSync
  • SetupWatcher on config file
  • call Harmony.PatchAll() - can be disabled via pathAll: false
  • Add config server lock
 private void Awake()
    {
        ModBase.CreateMod(_plugin: this, ModName, ModAuthor, ModVersion, pathAll: true);
        OnConfigurationChanged += () => {  };
    }

RunCommand

void RunCommand(Terminal.ConsoleEvent action, Terminal.ConsoleEventArgs args)
When you adding a new command, you can call this method to format it. It automatically uses try catch. throw new ConsoleCommandException to make error be shown only in in-game console. Any other exception will be shown in the log. Example:

    [HarmonyPatch(typeof(Terminal), nameof(InitTerminal))]
    [HarmonyWrapSafe]
    internal class TerminalCommands
    {
        private static void Postfix()
        {
            new ConsoleCommand("mycoolcommand", "", args => RunCommand(args =>
            {
                if (!IsAdmin) throw new ConsoleCommandException("You are not an admin on this server.");
                //Do something
            }, args));
        }
    }

GetPlugin

T GetPlugin<T>() where T : BaseUnityPlugin
BaseUnityPlugin GetPlugin()
Returns the plugin instance of type of BaseUnityPlugin or of type of T. T should your BaseUnityPlugin type.

GetPlugin<MyMod>().SomeMethodImplodedInMyMod();

Debug

void Debug(object msg, bool showInHud = false, bool showInConsole = false)
Logs message to the BepInEx console.

DebugError

void DebugError(object msg, bool showWriteToDev = true, bool showInConsole = false)
Logs error message to the BepInEx console.

DebugWarning

void DebugWarning(object msg, bool showWriteToDev = true, bool showInConsole = false)
Logs warning message to the BepInEx console.

DebugWarning

AssetBundle LoadAssetBundle(string filename)
Loads an asset bundle, returns the it and saves it in ModBase.bundle field.

CreateModGUID

string CreateModGUID(string ModName, string ModAuthor) => $"com.{ModAuthor}.{ModName}";
Constructs a mod GUID. in format com.ModAuthor.ModName.

Properties

ModName

string ModName { get; private set; }
The name of the mod.

ModAuthor

string ModAuthor { get; private set; }
The author of the mod.

ModVersion

string ModVersion { get; private set; }
The version of the mod.

ModGUID

string ModGUID { get; private set; }
The GUID of the mod.

Harmony

Harmony harmony { get; private set; }
The harmony instance for this mod.

IsAdmin

bool IsAdmin
Whether the player is an admin on this server.

Fields

bundle

AssetBundle bundle
The asset bundle of the mod set by LoadAssetBundle.

Events

OnConfigurationChanged

Action OnConfigurationChanged
Called when configuration file is changed.


TimeUtils

Made by Azumatt.
All methods are static.

Methods

GetCurrentTimeValue

(int, int) GetCurrentTimeValue()
Returns the current time in format HH.mm.


SimpleVector2

Simple struct for 2D vector.

Methods

ToSimpleVector2

UnityEngine.Vector2 ToVector2()
Converts to UnityEngine.Vector2.

ToString

string ToString()
Converts to string in format X: {X}, Y: {Y}

Fields

x

float x
X value.

y

float y
Y value.

ExtensionMethods

ToSimpleVector2

SimpleVector2 ToSimpleVector2(this UnityEngine.Vector2 vector2)
Converts UnityEngine.Vector2 to SimpleVector2.


SimpleVector3

Simple struct for 3D vector.

Methods

ToSimpleVector3

UnityEngine.Vector3 ToVector3()
Converts to UnityEngine.Vector3.

ToString

string ToString()
Converts to string in format X: {X}, Y: {Y}, Z: {Z}

Fields

x

float x
X value.

y

float y
Y value.

z

float z
Z value.

ExtensionMethods

ToSimpleVector3

SimpleVector3 ToSimpleVector3(this UnityEngine.Vector3 vector3)
Converts UnityEngine.Vector3 to SimpleVector3.


ObjectsInstances

Registers all activly loaded pickables, plants, doors, signs, containers, crafting stations and beds.

Properties

AllPickables

List<Pickable> AllPickables
List of all pickables.

AllPlants

List<Plant> AllPlants
List of all plants.

AllDoors

List<Door> AllDoors
List of all doors.

AllSigns

List<Sign> AllSigns
List of all signs.

AllContainers

List<Container> AllContainers
List of all containers.

AllCraftingStations

List<CraftingStation> AllCraftingStations
List of all crafting stations.

AllBeds

List<Bed> AllBeds
List of all beds.


ConsoleCommandException

If running console command using ModBase.RunCommand, you should throw this exception if some commands conditions are not met. It will be filtered from other exceptions and printed only in in-game console.


Wheather

Enum of all posible vanila weather.


ZoneSystemExtension

SetGlobalKey

void SetGlobalKey(string key, object value)
Sets the global key by string key.

GetGlobalKeyValue

string GetGlobalKeyValue(string key)
Gets the global key value by string key.

GetOrAddGlobalKey

string GetOrAddGlobalKey(string key, string defaultValue)
Gets or adds the global key by string key.

GetGeneratedLocationsByName

(Vector2i, LocationInstance)[] GetGeneratedLocationsByName(string key)
Gets all generated locations by name. Returns an array of turple with Vector2i and LocationInstance, the first one is the zoneId, the second one is the location data.

CreateValidPlacesForLocation

List<Vector3> CreateValidPlacesForLocation(string key, int count)
Returns valid places for location generated by vanilla algorithm.

GetWorldObjectsAsync

Task<List<ZDO>> GetWorldObjectsAsync(params Func<ZDO, bool>[] customFilters)
Task<List<ZDO>> GetWorldObjectsAsync(string prefabName, params Func<ZDO, bool>[] customFilters)
Returns ZDOs of all objects in world matching given filters. Should be awated.


BiomeExtension

GetLocalizationKey

string GetLocalizationKey()
Returns the localization key for given biome.


ObjectDBExtension

GetItem

ItemDrop GetItem(string name)
ItemDrop GetItem(int hash)
Returns item by name or hash.


ItemDropExtension

LocalizeName

string ItemDrop.LocalizeName()
string ItemDrop.ItemData.LocalizeName()
string ItemDrop.ItemData.SharedData.LocalizeName()
Returns localized name of m_itemData.m_shared.m_name.


MinimapExtension

ForceUpdateLocationPins

void ForceUpdateLocationPins()
Updates all location pins immediately.


PrivateAreaExtension

InsideActiveFactionArea

bool InsideActiveFactionArea(Vector3 point, Character.Faction faction)
Returns true if point is inside PrivateArea that is active and belongs to given faction.


RecipeExtension

ToList

List<(ItemDrop.ItemData.SharedData, int)> ToList()
Converts Recipe to list of (ItemDrop.ItemData.SharedData, int). First is item shared data, second is amount.


SkillsExtension

GetCustomSkill

Skill GetCustomSkill(string skillName)
Returns vanila or mod skill by given name.


StringExtension

Localize

string Localize(string key)
Returns localized string.

IsGood

bool IsGood(string str)
Returns true if string is not null and not empty.


ZNetSceneExtension

GetItem

ItemDrop GetItem(string name)
ItemDrop GetItem(int hash)
Returns item by name or hash.

GetCharacter

Character GetCharacter(string name)
Character GetCharacter(int hash)
Returns character by name or hash.


VectorExtension

ToV2

Vector2 ToV2()
Converts Vector3 to Vector2, but Vector2.y is set to Vector3.z.

ToV3

Vector3 ToV3()
Converts Vector2 to Vector3, but Vector3.z is set to Vector2.y and Vector3.x is set to 0.

RoundCords

Vector3 RoundCords()
Vector2 RoundCords()
Returns Vector3 or Vector2 with coordinates casted to int.

SetX, SetY, SetZ

ref Vector3 SetX(float x)
ref Vector3 SetY(float y)
ref Vector3 SetZ(float z)
ref Vector2 SetX(float x)
ref Vector2 SetY(float y)
Sets coordinates of Vector3 to given values.

DistanceXZ

float DistanceXZ(Vector3 pos, Vector3 otherPos)
float DistanceXZ(Vector3 pos, Transform otherPos)
float DistanceXZ(Vector3 pos, Component otherPos)
float DistanceXZ(Vector3 pos, GameObject otherPos)
Equals to Utils.DistanceXZ(Vector3 v0, Vector3 v1).


EnumerableExtension

MakeDictionary

Dictionary<TKey, TValue> MakeDictionary<TKey, TValue>
Converts IEnumerable<KeyValuePair<TKey, TValue>> to Dictionary<TKey, TValue>.

Random

T Random()
Returns random element from IList.

RoundCords

List<Vector3> RoundCords() List<Vector2> RoundCords() Rounds all vectors in the list using RoundCords()

GetString

string GetString<T>(string separator = ", ")
Joins all IEnumerable elements to string with separator.

Next

T Next<T>(T current)
Returns next element from IEnumerable sequence.

Nearest

T Nearest<T>(IEnumerable<T> list, Vector3 nearestTo)
Vector3 Nearest<Vector3>(IEnumerable<Vector3> list, Vector3 nearestTo)
Returns nearest element from IEnumerable list to given Vector3. T must inherit from Component.


GameObjectExtension

GetOrAddComponent

T GetOrAddComponent<T>() where T : Component
Returns the component of Type type. If one doesn't already exist on the GameObject it will be added.

AddComponentCopy

T AddComponentCopy<T>() where T : Component
Adds a new copy of the provided component to a gameObject and returns it.

GetPrefabName

string GetPrefabName<T>() where T : Component
string GetPrefabName()
Returns prefab name.


MonoBehaviourExtension

SetActiveGO

void SetActiveGO<T>(bool flag) where T : Component
Sets the active state of the GameObject.

ToggleActiveGO

void ToggleActiveGO<T>() where T : Component
Toggles the active state of the GameObject.


RectExtension

IsOverlapsingOther

bool IsOverlapsingOther(RectTransform b)
bool IsOverlapsingOther(RectTransform b, bool allowInverse)
Returns true if a and b are overlapping.

WorldRect

Rect WorldRect()
Calculate the world rect of a RectTransform.

SetToTextHeight

GameObject SetToTextHeight()
Sets rectTransform's size to TextMeshProUGUI's or regular Text's preferred height.


RendererExtension

Flash

void Flash(Color color, Color returnColor, float time = 0.3f, Action callback = null)
Flashes renderer with given color for given time. Gives back to returnColor color after time. TODO: lerb color


TransformExtension

FindChildByName

Transform FindChildByName(string name)
Returns child of parent with given name. Equals to Utils.FindChild(parent, name).

DistanceXZ

float DistanceXZ(Transform other)
float DistanceXZ(Component other)
float DistanceXZ(GameObject other)
float DistanceXZ(Vector3 other)
Equals to Utils.DistanceXZ(Vector3 v0, Vector3 v1).