Search code examples
c#unity-game-engine

You are trying to create a MonoBehaviour using the 'new' keyword. when making grid in unity


i am attempting to spawn a grid over some tiles and have it weed out tiles that cant be walked on. but it just keeps saying You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). im not sure how to fix this. ive tried a bunch of things but nothing seems to be working.

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

}

ive tried adding it as a game object and component as well as what unity suggests i add. but ether i messed up along the way or something cause i couldnt get it to work.


Solution

  • This is because Monobehaviors cannot exist without their respective GameObject, as they are GameObject components.

    From the docs:

    • MonoBehaviour is a base class that many Unity scripts derive from.
    • MonoBehaviours always exist as a Component of a GameObject, and can be instantiated with GameObject.AddComponent.

    To make your GridLines work, just drag it to the GameObject of interest in the editor, or with code:

    public class OtherComponent : MonoBehaviour
    {
        void Start()
        {
            gameObject.AddComponent<GridLines>();
        }
    }