![](/img/trans.png)
[英]How to convert json properties that are formatted in dot notation to a c# class
[英]How Do I Cast a Variable With Dot Notation? Unity C#
我将(我的游戏中 object 的速度)变量从一个脚本引用到另一个脚本。 它有 3 个部分: min
var、 max
var( min
和max
用于生成速度的随机数)和fallSpd
var(从min
和max
生成的随机数)。 它们都是浮点数,但是当我在第 16 行引用变量max
和min
时,出现此错误:
Assets\Destruction.cs(16,22): error CS0266: Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)
所以我投了min
并且它允许它。 但是,当我将max
转换为double
时,会出现以下错误:
Assets\Destruction.cs(16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
所以我不知道我应该如何施放它。
这是我引用的代码(仅包括重要部分):
using UnityEngine;
using System.Collections;
public class Losing : MonoBehaviour
{
public GameObject[] Addictions = new GameObject[5];
public Transform[] Transforms = new Transform[5];
public static float fallSpd;
public static float min = 0.1f;
public static float max = 0.4f;
private bool Lost = false;
private void Start()
{
for (int i = 0; i < 5; i++)
{
if (Lost != true)
{
Transforms[i].position = new Vector2(Random.Range(-4, 4), Random.Range(12, 31));
ChangeSpd();
}
}
}
public void ChangeSpd()
{
fallSpd = (float) Random.Range(min, max) * Time.deltaTime;
}
以及引用此脚本的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destruction : MonoBehaviour
{
public Transform[] Transforms = new Transform[5];
public GameObject PrayingMan;
public Losing losing;
private void OnCollisionEnter2D(Collision2D other)
{
Losing.min = Losing.fallSpd;
(double) Losing.max = Losing.min + 0.3; // i get all the errors on this line!
print("min: " + Losing.min + "max: " + Losing.max + "speed: " + Losing.fallSpd);
PrayingMan.GetComponent<Losing>().ChangeSpd();
}
}
如何修复这个错误?
你根本不需要做任何铸造。 只需将“0.3”更改为“0.3f”即可。 f 表示它是一个浮点数,但如果没有 f 它将被认为是一个双精度数。
你把它颠倒过来了,你的变量是一个float
,但是当你做Losing.min + 0.3
你正在创建一个双精度,默认情况下 .net 如果没有指定小数修饰符,则假定double
精度。
您有两个选择,将值转换为浮动或使用修饰符。 做演员你会做:
Losing.max = (float)(Losing.min + 0.3);
但是这样处理很浪费,最好是指定float修饰符:
Losing.max = Losing.min + 0.3f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.