您正在尝试使用“new”关键字创建 MonoBehaviour。统一制作网格时

问题描述 投票:0回答:1

我正在尝试在一些瓷砖上生成一个网格,并让它清除不能行走的瓷砖。但它只是一直说你正在尝试使用“new”关键字创建一个 MonoBehaviour。 这是不允许的。 MonoBehaviours 只能使用 AddComponent() 添加。我不知道如何解决这个问题。我尝试了很多东西,但似乎没有任何效果。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class GridLines : MonoBehaviour

{
   Node[,] grid;
   [SerializeField] int width = 25;
   [SerializeField] int length = 25;
   [SerializeField] float cellSize = 1f;
   [SerializeField] LayerMask obstacleLayer;

   private void Start()
   {
    GenerateGrid();
   }

   private void GenerateGrid()
   {
     grid = new Node[length, width];
     CheckPassableTerrain();
    }

   private void CheckPassableTerrain()
   {
        for (int y =0; y < width; y++)
        {
      for (int x = 0; x < length; x++)
        {
            Vector3 worldPosition = GetWorldPosition(x,y);
          bool passable = Physics.CheckBox(worldPosition, Vector3.one /2 * cellSize, Quaternion.identity, obstacleLayer);
          grid[x,y] = new Node();
          grid[x,y].passable = passable;
        }  
    }
     }  

   private void OnDrawGizmos()
    {
      if (grid == null) 
      {
        return;
      }
    for (int y = 0; y < width; y++)
    {
      for (int x = 0; x < length; x++)
            {
                Vector3 pos = GetWorldPosition(x, y);
                Gizmos.color = grid[x,y].passable ? Color.white : Color.red;
                Gizmos.DrawCube(pos, Vector3.one);
            }
        }
   }

    private Vector3 GetWorldPosition(int x, int y)
    {
        return new Vector3(transform.position.x + (x * cellSize), 0f, transform.position.z + (y * cellSize));
    }

}

我尝试将其添加为游戏对象和组件以及 Unity 建议我添加的内容。但是我一路上搞砸了或者其他什么原因导致我无法让它工作。

unity-game-engine gridview unityscript
1个回答
0
投票

如果类型

Node
Monobehaviour
类型,则必须
Instantiate
其预制件。 (如果它继承自 Monobehaviour)

否则,如果您不需要

Monobehaviour
类中的
Node
功能,则可以删除继承。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.