我正在撰寫將物件移動到隨機位置的代碼。我做了一個函式來決定隨機坐標并回傳它。但是,我認為函式和是沒有聯系在一起的。這是我試過的...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
Vector3 target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 target = random(target);
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
}
Vector3 random(Vector3 target)
{
float min = -100.0f;
float max = 100.0f;
float randomX = Random.Range(min, max);
float randomZ = Random.Range(min, max);
Vector3 target = new Vector3(randomX, 10.0f, randomZ);
return target;
}
}
這是我收到的錯誤訊息。
Assets\Movement.cs(31,17): error CS0136: A local or parameter named 'target' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
問題是您target在隨機方法中定義了一個新變數。您之前已將其定義為方法體中的引數。改變其中之一。
uj5u.com熱心網友回復:
這不是 unity 的問題,而是編譯器的問題。
在random(Vector3 target)和void Update()方法中,您正在定義新的“目標”變數,如下所示:
Vector3 target
所以編譯器告訴你這是不允許的。如果要更新目標變數,請洗掉前面的“Vector3”或選擇一個新名稱。
不清楚這個函式是如何作業的,但我認為最好在開始時宣告目標或將其宣告為公開,以便您可以為其分配開始位置。
我認為你想要的是這樣的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
// OPTIONAL: declare public so the editor will let you set a position
public Vector3 target;
// Start is called before the first frame update
void Start()
{
// OPTIONAL: you can set a start position
target = Vector3.zero;
}
// Update is called once per frame
void Update()
{
target = random(target);
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
}
Vector3 random(Vector3 par)
{
float min = -100.0f;
float max = 100.0f;
float randomX = Random.Range(min, max);
float randomZ = Random.Range(min, max);
return new Vector3(randomX, 10.0f, randomZ);
}
編輯:您現在不需要“隨機”函式的引數。所以也許你可以洗掉它
uj5u.com熱心網友回復:
您收到此錯誤的原因是您已經Vector3 target在random和update方法之外宣告為類成員。
如果您來自 JavaScript 之類的語言,則可以通過在內部作用域內宣告相同的 var 變數名稱來實作,但在 C# 中這是不可能的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365054.html
上一篇:Unity專案未加載
