Infuriating error with GetComponent

I don’t understand why I’m getting this error. I’ve typed the code exactly as it says in the glossary, and I’ve tried every suggestion for the same issues I’ve seen on StackExchange. Still, this error will not go away. The error is within MonoDevelop, and specifically referenced GetComponent or gameObject. When I write

public Rigidbody rb = gameObject.GetComponent<Rigidbody>();

The error reads:
“An object reference is required for the non-static field, method, or property ‘UnityEngine.Component.gameObject.get’”
And if I write

public Rigidbody rb = GetComponent<Rigidbody>();

It reads:
“An object reference is required for the non-static field, method, or property ‘UnityEngine.Component.GetComponent’”

Here is the whole script:

using UnityEngine;
using System.Collections;

public class RandomRotator : MonoBehaviour 
{
	public float tumble;

	public Rigidbody rb = gameObject.GetComponent<Rigidbody>();

	void start ()
	{
		rb.angularVelocity = Random.insideUnitSphere * tumble;
	}
}

Thanks for any help.

Orami's answer will work for you here. Basically, public variables are set as soon as a RandomRotator object is created - before any kind of constructor or initialization has occured. As far as the compiler is concerned gameObject doesn't even exist at that point in the execution. Primitive types (int, float, string) can be set at this point because the compiler knows what those are. You can also create new objects inside a public variable declaration (compiler can create those), but you cannot reference existing objects because the compiler does not know that they exist at this point.

2 Answers

2

try:

 using UnityEngine;
 using System.Collections;
 
 public class RandomRotator : MonoBehaviour 
 {
     public float tumble;
 
     public Rigidbody rb;
 
     void Start ()
     {
         rb = gameObject.GetComponent<Rigidbody>();
         rb.angularVelocity = Random.insideUnitSphere * tumble;
     }
 }

Or you can drag the rigidbody to the variable in the script in the inspector. You can not call code from the definition area of a variable - although you can set a default value to the basic data types.

Start() also needs an uppercase 'S'

Fixed... I just copy and pasted his code and did some quick edits.

Put the GetComponent code in the Start() function. Also the ‘s’ in Start needs to be uppercase.

If you are overwhelmed then I suggest you try and do one thing at a time. I see all the different unrelated questions that you are asking on UA. You need to finish one thing at a time.