I'd like to store and retrieve a value from a secondary plugin...Solved

I have this in one plugin:

string playMode = "pve";

private string GetPlayMode() {

	return playMode;

}

private void SetPlayMode(string newPlayMode) {

	playMode = newPlayMode;

}

And am calling these like so in another plugin:

[PluginReference] Plugin CoreManagePlayMode;

void Init() {

	if (CoreManagePlayMode?.Call("GetPlayMode") == "pve") {
		Puts("pve");
	} else {
		Puts("pvp");
	}

}

But whatever I try I get an error saying that `Cannot explicitly convert type 'object' to 'string'` - whatever I do I seem to get returned an object. How do I handle this so I get a string?

Thanks in advance.



private string GetPlayMode() {
    string playMode = "pve";
	return playMode;
}

I also have a method for setting the value, so the value presumably needs to live outside the get method. Ive updated the question to make that clearer...

The issue is that the Call method returns a value of type object, which is not comparable to a value of type string using the == operator. You can try comparing with the equals method, or casting the result to string.

I'm a bit stuck, how best to cast as a string? I tried:

if (CorePlayMode?.Call("GetPlayMode").ToString() == "pve") {
	Puts("pve");
} else {
	Puts("pvp");
}

// AND

if (Convert.ToString(CorePlayMode?.Call("GetPlayMode")) == "pve") {
	Puts("pve");
} else {
	Puts("pvp");
}

// AND

object orig = CorePlayMode?.Call("GetPlayMode");

string value = (string)orig;

if (value == "pve") {
	Puts("pve");
} else {
	Puts("pvp");
}

 

It always fails the comparison, but at least I don't get any cast errors any more :)



Merged post

Weird, if I add

var CorePlayMode = plugins.Find("CorePlayMode");

and get rid of

[PluginReference] Plugin CorePlayMode;
 
All of the examples above work... so what am I doing wrong?

Not sure if this is the issue, but generally you should access plugins in OnServerInitialized, not in Init, since the other plugin may not be fully loaded yet.

Hmm, I'm only using Init for testing - I'll try OnServerInitialized though.

Sort of happy to have got this working, but I'd rather have it working how it should/expected to work - don't want weird behaviour later.

Merged post

Well damn, changed it to OnServerInitialized with 

[PluginReference] Plugin CorePlayMode;

 

and everything working :) thanks!!!

I just need to remember to initialise my plugins with OnServerInitialized not Init (will need to see what other differences are).

Short and sweet is 

string playMode = (string)CorePlayMode?.Call("GetPlayMode");​
Locked automatically