在
完整的腳本檔案:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Graph : MonoBehaviour
{
[SerializeField]
Transform pointPrefab;
[SerializeField, Range(10,100)]
int resolution = 10;
Transform[] points;
points = new Transform[resolution];
void Awake()
{
float step = 2f / resolution;
var position = Vector3.zero;
var scale = Vector3.one * step;
for (int i =0; i < points.Length; i )
{
Transform point = Instantiate(pointPrefab);
position.x = (i .5f) * step - 1f;
position.y = position.x * position.x * position.x;
point.localPosition = position;
point.localScale = Vector3.one / 5f;
point.SetParent(transform, false);
}
}
}
編譯器真的不喜歡第 15 行。首先它說當前背景關系中不存在“點”,即使我之前在行中宣告過它。然后它說“invalid token = in class, struct, or member declaration”。然后它說“不能在變數宣告中指定陣列大小”。
uj5u.com熱心網友回復:
您正在嘗試直接在類中撰寫代碼。這是不允許的。
通常,您可以將欄位初始值設定項與欄位宣告結合起來:
Transform[] points = new Transform[resolution];
但是,實體欄位初始值設定項不能參考其他實體欄位。在普通類中,您需要使用建構式:
Transform[] points;
public Graph()
{
points = new Transform[resolution];
}
注意:正如 Ruzihm 在評論中指出的,由于這是一個MonoBehaviour,你應該避免使用建構式。相反,您應該將初始化放在AwakeorStart方法中。
Transform[] points;
void Start()
{
points = new Transform[resolution];
}
欄位 - C# 編程指南 | 微軟檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371044.html
