Chapter 4 GetComponent Problem

Hi, I am starting Chapter 4 and am having some trouble with the GetComponent Code. The two main problems is that the = is read as an invalid token, and the name GetComponent does not exist in the current context. How can I fix this?

Thanks.

That code should go between curly brackets, the error you’re getting about the wrong context is correct. You’re writing in the context of the class, not of a method or property.

This is what you have now:

void Start() {  }

public float moveSpeed = 50.0f;

private CharacterController characterController;
characterController = GetComponent<CharacterController>();

Here’s what it should be:

//Class context
//Declerating variables
public float moveSpeed = 50.0f;
private CharacterController characterController;

void Start()
{  
  //Method context
  //Executing Unity API code (GetComponent)
  characterController = GetComponent<CharacterController>();
}

By the way, you can just copy-paste the code here and use the code tag (CTRL + SHIFT + C) or use something like pastebin to share code snippets.

Hope that helps!
Cheers!

GetComponent finally works, and I am really enjoying the book.
Thank you for your response.