- Home /
Get Rigidbody2D component in script (c#)
Hello.
I have components in my player object like:
How can I acces in PlayerMovement.cs that RigidBody? How can I find it?
Thanks!
Answer by Landern · Mar 24, 2015 at 12:55 PM
You get a reference to it.
Since you have the PlayerMovement component on the same game object, GetComponent is your friend.
If you are able to store the reference in a field(variable) then you can reuse it has the script is called over and over again.
example in start(c#):
using System;
using UnityEngine;
public class HeadBob : MonoBehaviour
{
private Rigidbody2D myScriptsRigidbody2D;
void Start()
{
myScriptsRigidbody2D = GetComponent<Rigidbody2D>();
}
void Update()
{
myScriptsRigidbody2D.AddForce(new Vector3(6, 8, 1)); // just an example.
}
}
example in start(java/unityscript)
private myScriptsRigidbody2D : Rigidbody2D;
function Start()
{
myScriptsRigidbody2D = GetComponent.<Rigidbody2D>();
}
function Update()
{
myScriptsRigidbody2D.AddForce(Vector3(6, 8, 1)) // just an example.
}
but what if I have multiple GameObjects with RigidBodycomponent???
Your answer
Follow this Question
Related Questions
error CS0029: Trying to access component in parent - c# 2 Answers
Referencing a c# component script from JS script 2 Answers
error CS0103 when I try to use Rigidbody2D 1 Answer
Enemy variable remains null 1 Answer
Referencing in a prefab 1 Answer