A field intializer cannot reference...error

Seeing as I was literally running this code just fine I don’t really know why an error suddenly popped up… Here’s the code:

 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class MonsterAI : MonoBehaviour {
    	public Transform Player;
    	CharacterController controller = GetComponent<CharacterController>();
    	public int MoveSpeed = 1;
    	// Use this for initialization
    	void Start () {
    		
    		
    	}
    	
    	// Update is called once per frame
    	void Update () {
    		transform.LookAt (Player);
    		controller.Move (Vector3.forward * MoveSpeed * Time.deltaTime);
    		
    	}
    }

Dear abhishek7,

You Are Using A Character Controller. Use A Nav Mesh Instead. See If That Helps

-TCE

Seeing as I was literally running this
code just fine I don’t really know why
an error suddenly popped up

Nah, it could not have worked that way as posted(unless you had it unsaved originally), you can’t initialize a field with GetComponent from the instance variable. Set the field variable called “controller” in either your Awake or Start method.

If you did something like:

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

public class MonsterAI : MonoBehaviour {
	public Transform Player;
	CharacterController controller;
	public int MoveSpeed = 1;

	// Use this for initialization
	void Start () {
		controller = GetComponent<CharacterController>();
	}

	// Update is called once per frame
	void Update () {
		transform.LookAt (Player);
		controller.Move (Vector3.forward * MoveSpeed * Time.deltaTime);
	}
}

Calling the base GetComponent generic is totally fine in the Start method, this would allow all other scripts to call there Awake method first and at least be available.

The exception to what i mentioned above is to call a static method to get a reference to an object/value, but this is not the case here.