Home > Net >  Name doesn't exist in current context, but variable has been declared -- Multiple errors
Name doesn't exist in current context, but variable has been declared -- Multiple errors

Time:12-01

Was following along in enter image description here

Full script file:

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);
        }
    }
}

The compiler really doesn't like line 15. First it says "points" doesn't exist in the current context, even though I declared it in the line before. Then it says "invalid token = in class, struct, or member declaration". Then it says "array size cannot be specified in variable declaration".

CodePudding user response:

You are trying to write code directly within the class. That is not allowed.

Normally, you could join the field initializer with the field declaration:

Transform[] points = new Transform[resolution];

However, an instance field initializer cannot reference other instance fields. In this case, you would need to use a constructor:

Transform[] points;

public Graph()
{
    points = new Transform[resolution];
}

Fields - C# Programming Guide | Microsoft Docs

  • Related