Jump to content

[SOLVED] How to use values from overridden void methods


Recommended Posts

Hello modders, do any of you happen to know how to make the string ResourceName available for other methods?

TBhs7Ey.png

I have tried to use

OnLoad(ConfigNode node, out string ResourceName)

and

public string ResourceName { get; set; }

but to no avail.

 

Link to comment
Share on other sites

17 minutes ago, ExtremeTrader said:

 


public string ResourceName { get; set; }

 

Try this one but also remove "string" from the body of OnLoad:

public override void OnLoad(ConfigNode node)
{
    ResourceName = node.GetValue("resource");
}

That way you'll be setting the public (shared) property instead of a new temporary variable.

Link to comment
Share on other sites

12 minutes ago, HebaruSan said:

Try this one but also remove "string" from the body of OnLoad:


public override void OnLoad(ConfigNode node)
{
    ResourceName = node.GetValue("resource");
}

That way you'll be setting the public (shared) property instead of a new temporary variable.

Yes, I tried that, but when I try to Debug.Log it is null (node.GetValue("resource") returns "LiquidFuel" as it should). I'm pretty new to C# and oop in general, so I might be making some dumb mistake.

Link to comment
Share on other sites

3 minutes ago, ExtremeTrader said:

Yes, I tried that, but when I try to Debug.Log it is null (node.GetValue("resource") returns "LiquidFuel" as it should). I'm pretty new to C# and oop in general, so I might be making some dumb mistake.

When are you checking it? It will be null before OnLoad is called, for example if you check it in OnAwake.

Link to comment
Share on other sites

13 minutes ago, HebaruSan said:

When are you checking it? It will be null before OnLoad is called, for example if you check it in OnAwake.

I'm checking at OnStart which I thought came after OnLoad, but I could be wrong about that

Link to comment
Share on other sites

8 minutes ago, ExtremeTrader said:

I'm checking at OnStart which I thought came after OnLoad, but I could be wrong about that

Try it in Update, just in case. It's been a while since I worked with a PartModule, but I think there were some quirks with the order of some of those events.

Link to comment
Share on other sites

16 minutes ago, HebaruSan said:

Try it in Update, just in case. It's been a while since I worked with a PartModule, but I think there were some quirks with the order of some of those events.

It still doesn't, Debug.Log("[RT] onupdate " + ResourceName) only yields a spam of the string bit just like OnStart. I'll try reverse engineering another mod.

Edit: InterstellarFuelSwitch seems to call another method on load which puts inputs in variables that can be read in other scopes:

coVgLtb.png

Dictionaries and lists are too complicated for what I want, but I'll try the anothermethod-method tomorrow (2300 pm here)

Edited by ExtremeTrader
Link to comment
Share on other sites

1 hour ago, ExtremeTrader said:

It still doesn't, Debug.Log("[RT] onupdate " + ResourceName) only yields a spam of the string bit just like OnStart. I'll try reverse engineering another mod.

In that case, something is going on that isn't specified in the question so far. If OnLoad sets a property to a non-null value, it won't randomly become null again later. More code probably needs to be shared to figure this out.

Link to comment
Share on other sites

11 hours ago, HebaruSan said:

In that case, something is going on that isn't specified in the question so far. If OnLoad sets a property to a non-null value, it won't randomly become null again later. More code probably needs to be shared to figure this out.

This is all of my code currently:

using UnityEngine;

namespace ResourceTeleporter
{
    public class ResourceTransceiver : PartModule
    {
        public string ResourceName { get; set; }

        /// <summary>Load resource from config</summary>
        public override void OnLoad(ConfigNode node)
        {
            ResourceName = node.GetValue("resource");
            Debug.Log("[RT] OnLoad " + ResourceName);
        }

        /// <summary>Get resourceID from name</summary>
        public int GetResourceID(string ResourceName)
        {
            PartResourceDefinition Resource = PartResourceLibrary.Instance.GetDefinition(ResourceName);
            return Resource.id;
        }

        /// <summary>Get resources in the vessel this part is part of</summary>
        public double GetVesselResourceAmount(int ResourceID)
        {
            this.vessel.GetConnectedResourceTotals(ResourceID, out double amount, out double maxAmount);
            Debug.LogWarning("[RT] Current vessel resources: " + amount + " (max: " + maxAmount + ")");
            return amount;
        }

        public override void OnStart(StartState state)
        {
            Debug.Log("[RT] OnStart " + ResourceName);
        }

        public override void OnUpdate()
        {
            Debug.Log("[RT] OnUpdate " + ResourceName);
        }
    }
}

This returns (plus some relevant bits):

[LOG 10:54:19.149] PartLoader: Compiling Part 'Squad/Parts/Utility/rcsBlockRV-105_v2/rcsBlockRV-105/RCSBlock_v2' //ksp startup
[LOG 10:54:19.158] [RT] OnLoad LiquidFuel //the only time it works correctly


[LOG 10:55:09.555] [RT] OnStart //editor
[LOG 10:55:11.314] RCSBlock.v2 added to ship - part count: 4 //the part I attached the module to


[LOG 10:55:22.462] Loading ship from file: C:/Program Files (x86)/Steam/steamapps/common/Kerbal Space Program/KSP_x64_Data/../saves/default/Ships/VAB/Auto-Saved Ship.craft
[LOG 10:55:22.462] [UIMasterController]: HideUI
[LOG 10:55:22.491] [RT] OnLoad //switch from editor to flight


[LOG 10:55:25.946] [RT] OnStart //flight, gets spammed for every update so I just pasted one here


[LOG 10:55:26.259] [RT] OnUpdate //flight

ResourceTransceiver.ResourceName gets reset on scene switches apparently (it doesn't even get overridden like on the editor->flight switch, there is no OnLoad between startup and editor). It probably should have a KSPField property, I'm going to test that now.

edit: added [KSPField(isPersistant = true)] in the line before ResourceName, part did not compile (same thing with just [KSPField()]):


[LOG 11:17:09.478] PartLoader: Compiling Part 'Squad/Parts/Utility/rcsBlockRV-105_v2/rcsBlockRV-105/RCSBlock_v2'
[EXC 11:17:09.488] MissingMethodException: No constructor found for BaseField::.ctor(KSPField, System.Reflection.MonoProperty, ResourceTeleporter.ResourceTransceiver)
	System.Activator.CreateInstance (System.Type type, BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[] args, System.Globalization.CultureInfo culture, System.Object[] activationAttributes)
	System.Activator.CreateInstance (System.Type type, System.Object[] args, System.Object[] activationAttributes)
	System.Activator.CreateInstance (System.Type type, System.Object[] args)
	BaseFieldList`2[R,K].CreateList (System.Object instance)
	BaseFieldList.CreateList (System.Object instance)
	BaseFieldList`2[R,K]..ctor (System.Object host, Boolean ignoreUIControl)
	BaseFieldList`2[R,K]..ctor (System.Object host)
	BaseFieldList..ctor (UnityEngine.Object host)
	PartModule.ModularSetup ()
	PartModule.Awake ()
	UnityEngine.GameObject:AddComponent(Type)
	Part:AddModule(String, Boolean)
	Part:AddModule(ConfigNode, Boolean)
	PartLoader:ParsePart(UrlConfig, ConfigNode)
	<CompileParts>c__Iterator1:MoveNext()
	UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
[ERR 11:17:09.488] PartLoader: Encountered exception during compilation. System.NullReferenceException: Object reference not set to an instance of an object
  at PartModule.Load (.ConfigNode node) [0x00000] in <filename unknown>:0 
  at Part.AddModule (.ConfigNode node, Boolean forceAwake) [0x00000] in <filename unknown>:0 
  at PartLoader.ParsePart (.UrlConfig urlConfig, .ConfigNode node) [0x00000] in <filename unknown>:0 
  at PartLoader+<CompileParts>c__Iterator1.MoveNext () [0x00000] in <filename unknown>:0 

[ERR 11:17:09.489] PartCompiler: Cannot compile part

I could store ResourceName in a different class perhaps

Edited by ExtremeTrader
Link to comment
Share on other sites

50 minutes ago, ExtremeTrader said:

ResourceTransceiver.ResourceName gets reset on scene switches apparently

Close; the whole object is discarded and replaced. Note the new OnLoad call that's missing the resource:

[LOG 10:55:22.491] [RT] OnLoad //switch from editor to flight

That means you've got a new instance of the class, loaded from a ConfigNode without a "resource" property.

Try overriding OnSave to store your property's value, so it'll be there when the flight scene starts:

public override void OnSave(ConfigNode node)
{
    node.SetValue("resource", ResourceName, true);
}

 

Link to comment
Share on other sites

2 hours ago, HebaruSan said:

Close; the whole object is discarded and replaced. Note the new OnLoad call that's missing the resource:


[LOG 10:55:22.491] [RT] OnLoad //switch from editor to flight

That means you've got a new instance of the class, loaded from a ConfigNode without a "resource" property.

Try overriding OnSave to store your property's value, so it'll be there when the flight scene starts:


public override void OnSave(ConfigNode node)
{
    node.SetValue("resource", ResourceName, true);
}

 

Nothing. I feel like [KSPField()] is the way to go, but everything I try ends up in the part not being loaded :/. When using KSPField, OnLoad and OnSave should not be necessary so I will try removing those.

I tried adding [KSPModule("Resource Transceiver")] too, but that did not do anything about the error.

 

Edit: I commented out OnLoad and OnSave, now everything outputs LiquidFuel as it should, and it shows up in the .craft file too. Thanks for the help!

Edited by ExtremeTrader
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...