Home > Back-end >  Getting Error: "Operator '||' cannot be applied to operands of type 'string'
Getting Error: "Operator '||' cannot be applied to operands of type 'string'

Time:08-30

I'm trying to run a test script for my game and I keep getting the error:

Operator '||' cannot be applied to operands of type 'string' and 'string'

Here's the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed;
    private string currentState;
    const string PLAYER_JAB = "Jab";
    const string PLAYER_KICK = "Kick";

    // ...

    void Update()
    {
        // ...

        //No Moving while Attacking
        if (currentState = PLAYER_JAB || PLAYER_KICK)
        {
            speed = 0;
        }
    }
}

I know for a fact the error has something to do with line 73, and that I can't use the || sign with strings, but I'm not sure how I can rearrange it to make it work. Can anyone help?

CodePudding user response:

There are 2 issues in your code:

  1. In order to compare, you need to use ==, not = (which is the assignment operator).
  2. You need to use == for comparing with each of the values, and then use the logical or (||) between the 2 comparissons.

Therefore you need to replace this line:

if (currentState = PLAYER_JAB || PLAYER_KICK)

With:

if (currentState == PLAYER_JAB || currentState == PLAYER_KICK)

Your line above is attempting to assign currentState with the logical or between 2 strings, which is not valid.

CodePudding user response:

You are correct. It is definitely line 73.
What you are actually doing is trying to set the value of currentState, which is a string, to a boolean value, which you can't do. The boolean value you are trying to set it to is the value of PLAYER_JAB (a string) OR'ed with PLAYER_KICK (also a string). You cannot OR a string with another string.

  • Related