Rigidbody changes reference in play time to the game object that the script is attached to
Hi, I have recently started programming on unity again and I'm getting this annoying error. It has no error message. It's probable something that I've done wrong I just can't figure it out. Any help would be greatly appreciated. Thank you, Marshall.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class fef : MonoBehaviour { public Rigidbody a; public Rigidbody b; public Rigidbody c;
// Start is called before the first frame update
void Start()
{
a = GetComponent<Rigidbody>();
b = GetComponent<Rigidbody>();
c = GetComponent<Rigidbody>();
}
}
Answer by highpockets · May 30, 2019 at 07:54 AM
Well, you are likely setting all these rigidbodys in the inspector, but right when you press start. The void Start() function is setting each of those rigidbody variables to the rigidbody that the script it is attached to the game object which the script is attached to. To avoid this, just delete what you have in the Start method. Just putting "`GetComponent();`" is short hand for "`this.GetComponent();`", but since you are already setting up the connection in the inspector, you don't need to do it again in the start method anyways. If you were doing it in the start method, you would need to reference the object first. You could use FindObjectOfType()
or GameObject.Find("NameOfObjectInScene").GetComponent<Rigidbody>();