Search Unity

`!' operator cannot be applied to operand of type `string'

Discussion in 'Scripting' started by Muber Gaming, Nov 22, 2014.

  1. Muber Gaming

    Muber Gaming

    Joined:
    Jan 24, 2014
    Posts:
    48
    Hi guys, got another couple of questions:

    i am trying to do a very simple user login system against stored server player prefs database.
    i know this is not the best but for now is all i need.

    first how can i fix this compiler error:
    The `!' operator cannot be applied to operand of type `string'
    Code (CSharp):
    1.  if (!PlayerPrefs.GetString(Username) )
    Code (CSharp):
    1.     [RPC]
    2.     public void LoginIRequest(string Username, string Password)
    3.     {
    4.         if (!PlayerPrefs.GetString(Username) )
    5.         {
    6.             Debug.Log("Login request Username does not exist in player prefs");
    7.             networkView.RPC("SendInvalidUserInfo",RPCMode.All,Username);
    8.             return;
    9.         }


    second, will the return statement in bottom be enough or the right way to halt the process if no user found in player prefs?


    thanks in advanced
     
  2. Stoven

    Stoven

    Joined:
    Jul 28, 2014
    Posts:
    171
    You're using the logical not '!' operator on a method that returns a string, which is why you're getting that error.

    Depending on what PlayerPrefs.GetString returns if the key doesn't exist, you can try one of the following approaches:

    [If it returns null] Simply use PlayerPrefs.GetString(Username) == null

    [If it returns a 0-length string] Simply use PlayerPrefs.GetString(Username).Length == 0
     
    Muber Gaming likes this.
  3. SeriousBusinessFace

    SeriousBusinessFace

    Joined:
    May 10, 2014
    Posts:
    127
    Unity's C# objects most/all convert to boolean (true if not null, false if null), which is why you can use the not '!' operator on them. Most of the default C# library, including strings, don't convert to boolean.
     
    Muber Gaming likes this.
  4. Muber Gaming

    Muber Gaming

    Joined:
    Jan 24, 2014
    Posts:
    48
    thanks Stoven,

    the second option worked for me.

    much appreciated.

    regards
     
  5. MakeCodeNow

    MakeCodeNow

    Joined:
    Feb 14, 2014
    Posts:
    1,246
    Best to use string.IsEmptyOrNull() for this kind of check.
     
    Magiichan, Muber Gaming and Stoven like this.