![](/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.