Toon de Jonge
Toon de Jonge

Reputation: 35

C# Unity error: Operator '-' cannot be applied to operands of type 'int' and 'string'

In my 2D game platformer I have a timer that counts down from 60s to 0s. There are also powerups that the player can collect. One of the powerup is that if the player picks it up, it gives the player +5s extra time. I understand the error but I don't know out how to deal with. This is the error: timy.currentTime = timy.currentTime - 5;

Error in Visual Studio: 2 Operator '-' cannot be applied to operands of type 'string' and 'int'

GameManger script (here is the timer etc)

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour
{
  // TIMER
  public GUISkin skin;

  public Rect timerRect;

  public Color warningColorTimer;
  public Color defaultColorTimer;

  public static float startTime = 60;
  public string currentTime;

  // Update is called once per frame
  void Update()
  {
    startTime -= Time.deltaTime; // DeltaTime = lengte van de laatste frame
    currentTime = string.Format("{0:0.0}", startTime);

    if (startTime <= 0)
    {

      startTime = 60;


    }
  }

  void OnGUI ()
  {
    GUI.skin = skin;

    GUI.Label(timerRect, currentTime); 
  }
}

ExtraTime script

using UnityEngine;
using System.Collections;

public class ExtraTime : MonoBehaviour
{
  GameManager timy = new GameManager();

  void OnTriggerEnter2D(Collider2D other)
  {
    if (other.tag == "Player")
    {
      timy.currentTime = timy.currentTime - 5;
      Destroy(this.gameObject);

    }
  }
}

Upvotes: 0

Views: 1139

Answers (2)

Loki
Loki

Reputation: 615

You must either store currentTime as numerical value, or convert it to one, do the math, and convert back to string

Upvotes: 3

Juan
Juan

Reputation: 3705

Your current time variable is of type string, try changing it to int:

public string currentTime;

To

public int currentTime;

You will need to drop the following too:

currentTime = string.Format("{0:0.0}", startTime);

Startime is a numeric format already, although is float so you could require some conversion here.

Upvotes: 3

Related Questions