Why does this code dont work
I want to create an object and make him move forward like the classic bullet
using UnityEngine; using System.Collections;
public class shooting : MonoBehaviour { public GameObject cat; public bool create = false; public float speed = 180;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
Instantiate(cat,transform.position, Quaternion.identity);
cat.AddComponent<Rigidbody>();
Rigidbody cat_rigidbody = cat.GetComponent<Rigidbody>();
cat_rigidbody.AddForce(transform.forward * speed * Time.deltaTime);
Destroy(cat,10.0f);
}
Answer by JedBeryll · May 21, 2016 at 06:30 PM
Because you try to move the original object.
Instantiate(cat,transform.position, Quaternion.identity);
The above code returns the instance but you don't save it and you don't move it. Instead you move the original "cat". You could do:
GameObject newCat = Instantiate(cat,transform.position, Quaternion.identity);
and then add the rigidbody to the newCat. By the way, AddComponent also returns the added component so you can do this in one line like this:
Rigidbody cat_rigidbody = cat.AddComponent<Rigidbody>();
Answer by Picatti · May 21, 2016 at 08:13 PM
void Update () {
if (Input.GetMouseButtonDown(0)) {
GameObject newcat = Instantiate(cat,transform.position, Quaternion.identity);
Rigidbody cat_rigidbody = newcat.Add.Component<Rigidbody>();
cat_rigidbody.AddForce(transform.forward * speed * Time.deltaTime);
Destroy(cat,10.0f);
}
it doesn't work :(
AddForce takes another parameter. By default it's "Force" which would work if you applied it continouosly, give it an "Impulse" or "VelocityChange". http://docs.unity3d.com/ScriptReference/Force$$anonymous$$ode.html
cat_rigidbody.AddForce(transform.forward * speed * Time.deltaTime, Force$$anonymous$$ode.Impulse);
Also at the end, you probably want to destroy the newCat not the original.
Your answer
Follow this Question
Related Questions
Player i spining when moving 0 Answers
VR game controller tracking doesn't work 0 Answers
How do I change my NavMesh Agent from one NavMesh to another? 0 Answers
Photon Player Mover Failure 1 Answer
help with player movement 0 Answers