Accessing Another GameObjects Rigidbody

So I have a Sphere which has a Rigid-body attached to it. I’m Trying to access that Rigid-body in another script which is attached to a cube object. The reason I’m doing this is to add a force to the sphere when the sphere touches the cube. I thought this would be simple, but I’m pretty new to C#. It REFUSES to recognize the Rigid-body as a valid thing. Here is the code:

using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour
{
    public int Height = 10;
    public GameObject dude;
    public Rigidbody Rb = dude.GetComponent<Rigidbody>();
}

The error says: A field initializer cannot reference the non-static field, method, or property ‘Jump.dude’

You can’t reference a field instance for a field value, this is what constructors are for or in the case of Unity, Start/Awake.

Modify your script to look like:

 using UnityEngine;
 using System.Collections;
 
 public class Jump : MonoBehaviour
 {
     public int Height = 10;
     public GameObject dude;
     public Rigidbody Rb;

     void Start()
     {
         Rb = dude.GetComponent<RigidBody>();
     }
 }

Or you declare it sa public and assign it via inspector, or you declare (public or private) and assign it via code.

One thing is declare a variable, the other thing is to define its value (asign or refear a component to a variable its defining its value)

public Rigidbody Rb; ← Declaration

Rb = dude.GetComponent(); ← Definition

This isn’t a direct answer to your question, but I want to warn you, this isn’t good design. When two objects interact, it’s best to define the effect in the components for the game object. you can set a tag or something, or send an Event message, or define a method which is called by the script. Study Unity - Scripting API: Collision

This is important because if something strange starts happening to an object, if your program gets more complex, you have to explore the whole scene, not just the object.

Unity’s 3d Game Kit is helpful here. They implement damager.cs and destructible.cs, for example–you write code for the object to reduce it’s own value or destroy itself if struck.