C# - not allowed to call this function error when referencing another script

Hi - I’m trying to make a script attached to the game camera available to another script. In the class, I declare two variables:

using UnityEngine;
using System.Collections;

    public class HeadLookController : MonoBehaviour {
    	
    	public GameObject gameCam;
    	public UnityOSCReceiver oscScript;

void LateUpdate(){
gameCam = GameObject.Find("MainCamera");
gameCam.GetComponent("UnityOSCReceiver") as UnityOSCReceiver;
}

    }

Which then creates an error for the object that’s calling the script:

/*
UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don't use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
CursorHit..ctor ()
*/

How do I access the script? Never worked in c# before so it’s tripping me up a bit.

try moving this code into the “Start()” function instead of update and see if u still get the error

The error advice you to change those declaration to the awake or start funcion. Did you tried to do that ? Take care!

Is it actually finding my script?

No, it’s not, which is why you’re seeing a null log.

Relooking at your code, there’s a bit of an obvious omission, and would explain why you’re getting null, assuming you’ve transferred this exactly to start:

void Start()
{
   gameCam = GameObject.Find("MainCamera");
   gameCam.GetComponent("UnityOSCReceiver") as UnityOSCReceiver;
}

That second line gets the component (if it actually exists on your camera, have you checked that?) but you’re not actually assigning it. Also, from a stylistic and performance point of view, I’d suggest rather using the generic version of GetComponent. You also don’t need to keep the reference to the main camera if you’re not going to use it again in your code. So you could replace the above with:

// Remove "public GameObject gameCam;" from your class definition first
public void Start()
{
  GameObject gameCam = GameObject.Find("MainCamera");
  if (null != gameCam) osScript = gameCam.GetComponent<UnityOSCReceiver>();
}