Question about refering to another Gameobject

Hello!

So, I have this problem, and I’m checking out different topics but I can’t seem to find the answer. I’m really new to the engine, and I’ve come across something I do not know how to solve. :slight_smile:

I’ve created a cube called Sten, with a script. Within this script I’d like to add force to another object called Potato (without attaching the script to the Potato in the inspector). I’ve managed to rotate it through transform, but I fail to add force to it - even though it has a rigid body in the inspector. If I try to add “public Rigidbody spud”; it already says I’m using that variable - so I’m a bit in the fog right now.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player_movement : MonoBehaviour
{

  public Rigidbody physicalmodel;
  private float powerforce=100f;
  public GameObject spud;
 


    // Start is called before the first frame update
    void Start()
    {
  spud = GameObject.Find("Potato");
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (Input.GetKey("space"))
        {
          physicalmodel.AddForce(Vector3.forward * powerforce);
          spud.transform.Rotate(0, 100 * Time.deltaTime, 0);
          spud.AddForce(Vector3.forward * powerforce);
        }
    }
}

‘spud’ is a GameObject. AddForce does not exist inside the GameObject class (right-click on GameObject and select Go To Definition in VS to see the properties/functions it gives you). AddForce exists inside the Rigidbody class.

So you would have to put spud.GetComponent().AddForce…

But you don’t want to use GetComponent every FixedUpdate frame. It’s potentially bad for performance.

So make line 17 ‘spud = GameObject.Find(“Potato”).GetComponent();’, and change spud to a Rigidbody type instead of GameObject.

Ah, It works. So much refering to stuff in this engine compared to Gamemaker. :stuck_out_tongue: Thank you!