Unity C#脚本编译错误:points已声明却提示不在当前上下文 存在多个报错
报错原因
- C#语法不允许在类的直接作用域下,单独给已声明的成员变量执行赋值操作:类中只能在声明变量的同时完成初始化,或者在类的方法、构造函数、生命周期函数内部执行赋值。你将
points = new Transform[resolution];直接写在类作用域下,不属于任何代码块,编译器会识别为非法的成员声明,因此抛出invalid token = in class, struct, or member declaration错误。 - 非静态的成员变量
resolution无法在类作用域下直接用于初始化其他成员,你在类作用域下初始化数组时读取resolution的值属于非法操作,也会触发变量不存在、数组长度无法声明的报错。
解决方法
将points = new Transform[resolution];这行代码移动到Awake()方法的第一行即可。
修正后的完整代码如下:
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; void Awake() { points = new Transform[resolution]; float step = 2f / resolution; var position = Vector3.zero; for (int i =0; i < points.Length; i++) { Transform point = Instantiate(pointPrefab); position.x = (i + 0.5f) * step - 1f; position.y = position.x * position.x * position.x; point.localPosition = position; point.localScale = Vector3.one / 5f; point.SetParent(transform, false); } } }
内容的提问来源于stack exchange,提问作者DJG
相关产品推荐
相关产品推荐

