- Home /
Calling non-static from static function C#
I can't call LogUser and ErrorMessage inside of LoginResultListener because it is static and they aren't, but i can't make LogUser and ErrorMessage statics because they call functions inside that can be called only from main thread. What should i do?
Core.cs
private void ReceiveData()
{
int numberOfBytesRead = 0;
while (isConnected && _stream.CanRead)
{
try
{
numberOfBytesRead = _stream.Read(_buffer, 0, _buffer.Length);
receiveMsg = Encoding.ASCII.GetString(_buffer, 0, numberOfBytesRead);
_stream.Flush();
string[] OpHandler = receiveMsg.Split('#');
switch(OpHandler[0]) {
case LOGIN:
Login.LoginResultListener(true, receiveMsg);
break;
}
Array.Clear(OpHandler, 0, OpHandler.Length);
receiveMsg = "";
}
catch (Exception e)
{
CloseConnection();
}
}
}
Login.cs
public GameObject error_message;
void LogUser() {
SceneManager.UnloadScene("login");
SceneManager.LoadScene("game", LoadSceneMode.Additive);
}
void ErrorMessage() {
error_message.GetComponent<Text>().text = "error";
}
public static void LoginResultListener(bool result)
{
if (log_submitted)
{
switch (result)
{
case true:
LogUser();
break;
case false:
ErrorMessage();
}
}
}
I don't know the definitive answer since I don't have much experience with threading so this is just an educated guess. If using statics is out of the question for methods that work with threading (and also non static members of a class), then that should cascade up right? (For methods that use methods ...etc., that end up working with threading) So, wouldn't your only option be making LoginResultListener not static?
As a side note I just wanted to say, switch on a boolean value? Now, that's one I have never seen before. Why not a simple if/else? It's less indentation, less lines and clearer in this case I$$anonymous$$HO.
Answer by Buckslice · Nov 29, 2017 at 01:59 AM
I tried out a modified version of your code and made LogUser() and ErrorMessage() static functions and it seemed to work fine. What kind of error message are you getting?
Answer by icra · Nov 29, 2017 at 08:59 PM
The problem was i had to call methods that could be called only on main thread, so i couldn't on static functions. I solved with a Queue.
Your answer
Follow this Question
Related Questions
C# Going Static or Going OOP 3 Answers
Can't Encode MD5 2 Answers
An object reference is required to accsess a non-static member 'Lives.loselife()' 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers