Home > Back-end >  Problems with converting string to int
Problems with converting string to int

Time:11-08

I am trying to convert a string to a int like this in Unity (thank you Franz Gleichmann for answering twice now i've got new errors) here is the code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;

public class Move : MonoBehaviour {

    SerialPort sp = new SerialPort("/dev/tty.usbmodem1411", 9600); // set port of your arduino connected to computer
    
    public bool on = false;
    public int speed = 0;
    public string A;
    public string B;

    void Start () {
        sp.Open();
        sp.ReadTimeout = 1;
    }

    void Update () {
        A = sp.ReadLine();
        if (sp.IsOpen) {
            try {
                if (on) {

                    bool isParsable = Int32.TryParse(A, out B);

                    if (isParsable)
                    {
                        Console.WriteLine(B);
                    }
                    else
                    {
                        Console.WriteLine("Could not be parsed.");
                    }
                    transform.Translate(Vector3.left   (Time.deltaTime * B / speed));   //error on this line
                    
                }
            } catch (System.Exception) {
            }
        }
    }
}

The aim of this script is to take a number from a USB and move an object by that amount. However, Unity gives me this error:

Assets/scripts/Move.cs(37,41): error CS0019: Operator ' ' cannot be applied to operands of type 'Vector3' and 'float'

Any answers will help, if you want you can write your own version of the script. Thanks.

CodePudding user response:

If you check the c# documentation of the Int32.TryParse function, you will notice the second parameter is of type Int32.

Your error:

CS1503: Argument 2: cannot convert from 'out string' to 'out int'

Is telling that your B variable should be Int32 to be able to store the result of the Int32 data.

public string A;
public Int32 B;

When you change that B variable to a numeric type, your second error Operator '*' cannot be applied to operands of type 'float' and 'string' raised at this line would also dissapear.

transform.Translate(Vector3.left   (Time.deltaTime * B / speed));

Some advice: You should start giving more meaningful names to your variables.

CodePudding user response:

You must use int instead of Int32 So your code should look like this

bool isParsable = int.TryParse(A, out B);
  • Related