- Home /
Creating ball prefab and assigning it a rigidbody
Hey, so I'm doing an online gamedev course and I'm having some trouble understanding a bit of code. I numbered each line of code and the comments/questions are below with the corresponding number.
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
1 GameObject Instance = Instantiate(ballPrefab);
2 Rigidbody rb = Instance.GetComponent<Rigidbody>();
3 rb.velocity = Vector3.left*speed;
}
So on this line, Instantiate creates a ball prefab and assigns it to the GameObject Instance, correct?
This takes the ball prefab that was assigned the name Instance and assigns it a rigidbody, or is it just creating a rigidbody to be assigned later on? This line is where I'm most confused.
Takes the rigidbody object and assigns it a velocity.
Answer by danmw3 · Apr 07, 2017 at 03:43 PM
Instantiate creates a clone of the prefab you provide. The prefab is in the form of a GameObject and the clone is in the form of a GameObject. So on line one you are creating a clone of ballPrefab and assigning it to a local variable called Instance which is a GameObject.
GetComponent attempts to retrieve a specified component(script) from a GameObject. If the component does not currently exist on the GameObject then it will provide a null value. So on line two you are attempting to grab the Rigidbody component and assign it to a local variable called rb which is a Rigidbody.
You are on the right track and I hope this clears some things up. Here are the Unity API docs for future reference: https://docs.unity3d.com/ScriptReference/
Your answer
Follow this Question
Related Questions
Surface interaction between rotating RigidBodies? 0 Answers
How do I change Raycast's direction based on movement input? 1 Answer
Unity 5 - Sliding Rigidbodies with maximum friction 2 Answers
RigidBody immediately stops after AddForce 1 Answer
Looking for some advice for a Horse with Rigidbody 0 Answers