Jump to content

Resource consumption example code


Recommended Posts

Can anyone reply with example source on how to write a resource consumer code ?

I need it in form of custom code that will both consume a resource under specific conditions and manage loading/saving to/from persistence and vessel cfg (i already know how to handle load/save, i just mentioned it so it may be known in advance what my code needs to do).

And if resource generation is also not so much different from consumption code,  an example for that too would be appreciated.

Edited by fatcargo
Link to comment
Share on other sites

Here's a bare skeleton. You'll also need to add code to handle turning the isRunning flag on/off etc. Persistence of resource values is automatic so no need to add anything for that.

public class MyPart : PartModule
{
	[KSPField(isPersistant = true, guiName = "Running", guiActive =true)]
	public bool isRunning;
	
	[KSPField]
	public string requiredResourceName = "ElectricCharge";
	
	[KSPField]
    public double powerConsumption = 10f; // 10 units/s
	
	void FixedUpdate()
	{
		if (isRunning)
		{
			// power consumption
			var required = TimeWarp.deltaTime * powerConsumption;
			if (ResourceAvailable(requiredResourceName) > required)
				RequestResource(requiredResourceName, required);
			else
				OnNoPower();
		}
	}
	
	private double ResourceAvailable(string resource)
	{
		var res = PartResourceLibrary.Instance.GetDefinition(resource);
		double amount, maxAmount;
		part.GetConnectedResourceTotals(res.id, out amount, out maxAmount);
		return amount;
	}

	private float RequestResource(string resource, double amount)
	{
		var res = PartResourceLibrary.Instance.GetDefinition(resource);
		return (float)this.part.RequestResource(res.id, amount);
	}
	
	private void OnNoPower()
	{
		ScreenMessages.PostScreenMessage($"Not enough {requiredResourceName}"), 5f, ScreenMessageStyle.UPPER_CENTER);
		isRunning = false;
	}
}

Note this is not optimised. Caching the resource getdefinition would be one place to start.

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...