0

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);

    }
  }
}
2
  • 2
    Since currentTime is a string, it is obviously normal. How about parsing to int first if it is valid integer? Why do you need to format it at all? Mar 9, 2015 at 12:43
  • 3
    Or changing currentTime to not be a string to start with...
    – Jon Skeet
    Mar 9, 2015 at 12:44

2 Answers 2

3

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.

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.