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.
– jdean300