Hello!
I am trying to make a object move, by adding a Rigidbody component to the object:
Rigidbody rb = gameObject.AddComponent();
And then i reference the Rigidbody and add a force:
rb.AddForce(0, 0, 200 * Time.deltaTime);
I get the following error
This looks a bit fishy. Where is this executed?
Generally, it’s hard to say what’s going on without seeing the script or at least a part of it. Can you provide it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Force : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
Rigidbody rb = gameObject.AddComponent();
rb.AddForce(0, 0, 200 * Time.deltaTime);
}
}
ouch, wrong place, put the add component in the Start.
Doing a check to see if it exists would help as well
What you are doing here is adding new Rigidbody to a gameobject on every FixedUpdate. That might cause some problems. You only need to add it once. For example, in a Start function:
public class Force : MonoBehaviour
{
Rigidbody rb;
// Use this for initialization
void Start () {
rb = gameObject.AddComponent<Rigidbody> ();
}
// Update is called once per frame
void FixedUpdate () {
rb.AddForce(0, 0, 200 * Time.deltaTime);
}
}
Please use code tags.
I would, but i couldnt find them, i realized theyre under “insert”
[ code] your code here [ /code]
no spaces before the word code]