KingBarou13
KingBarou13

Reputation: 1

Getting Error: "Operator '||' cannot be applied to operands of type 'string' and 'string'"

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?

Upvotes: 0

Views: 105

Answers (2)

wohlstad
wohlstad

Reputation: 28094

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 comparisons.

Therefore you need to replace this line:

if (currentState = PLAYER_JAB || PLAYER_KICK)

with:

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

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

Upvotes: 4

Kevin
Kevin

Reputation: 7309

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.

Upvotes: 1

Related Questions