You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中字符串转int开发时出现CS0019运算符报错问题求助

解决方案

报错根因

CS0019报错是因为类型不匹配:Vector3.left是三维向量类型,而Time.deltaTime * B / speed的计算结果是浮点型,两种类型不能直接使用+运算符相加,你需要把速度系数乘到方向向量上而非直接相加。
除此之外代码还存在多个隐藏问题:

  • Int32.TryParse的输出参数要求为int类型,你当前声明的B是string类型,存在类型不匹配问题
  • sp.ReadLine()写在try块外部,串口读取超时抛出的异常无法被捕获,会直接导致程序闪退
  • speed默认值为0,直接参与除法运算会触发除零错误
  • 字符串解析失败的分支没有做拦截,解析失败时依然会用错误的B值参与移动计算
  • Unity中控制台输出需要用Debug.Log,Console.WriteLine不会在Unity控制台显示内容

修改后可直接运行的代码

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); 
    
    public bool on = false;
    // 默认速度调整为非0值,避免除零错误
    public int speed = 10;
    public string A;
    // B类型修改为int,适配TryParse的输出要求
    public int B;

    void Start () {
        // 打开串口前先判断状态,避免重复打开报错
        if (!sp.IsOpen)
        {
            sp.Open();
            sp.ReadTimeout = 1;
        }
    }

    void Update () {
        if (sp.IsOpen) {
            try {
                // 串口读取逻辑移到try块内,捕获读取超时异常
                A = sp.ReadLine();
                if (on) {
                    bool isParsable = Int32.TryParse(A, out B);
                    if (isParsable)
                    {
                        Debug.Log(B);
                        // 修正移动逻辑:速度系数乘到方向向量上
                        transform.Translate(Vector3.left * (Time.deltaTime * B / speed));
                    }
                    else
                    {
                        Debug.Log("Could not be parsed.");
                    }
                }
            } catch (System.Exception) {
                // 无特殊需求可以静默吞掉串口读取超时异常
            }
        }
    }

    // 脚本销毁时关闭串口,避免端口被占用
    private void OnDestroy() {
        if (sp.IsOpen)
        {
            sp.Close();
        }
    }
}

内容的提问来源于stack exchange,提问作者Boblet67

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:06:04