- Home /
When cloning, how do you make your clones keep the original properties?
Hello,
I am trying to clone an object, and I want the clone to have the same velocity as the original object, but every time I try, the clone is not keeping the original velocity. How can I solve this?
Thank you for your responses!
Answer by MichaelJT · Apr 07, 2015 at 06:53 PM
Have you considered attaching a script directly to the mouse object's prefab which sets is velocity as soon as its spawned?
private Rigidbody rb; // Reference to the rigidbody void Start () { rb = GetComponent <Rigidbody> (); // Sets up the rigidbody reference rb.velocity = new Vector3 (0f, 10f, 0f); // Sets the objects velocity on creation } }
The alternative is to make sure you get the rigidbody component on every object you spawn.
Add
tempRigidbody = clone.GetComponent <Rigidbody>(); tempRigidbody.velocity = new Vector3 (0, 10, 0);
into your instantiate function and it should work.
You are a life saver! I followed your first method and it worked like a charm. Thank you so much! Can't tell you how many days I've been stuck on this bug.
Answer by Owen-Reynolds · Apr 07, 2015 at 02:52 PM
Instantiate copies what it copies, and you can't change that. Pretty much, the stuff you can't see in the Inspector isn't copied by Instantiate -- dynamic physics settings and private script variables.
But, you can easily just copy over the values yourself, after the Instantiate.
I see. I made a script for the transform to move at a certain velocity, and the velocity is a public variable. But even when I tried to instantiate it, the clones won't carry over that velocity. $$anonymous$$aybe I'm doing something wrong.
So I did this ins$$anonymous$$d(which still doesn't work):
Rigidbody2D clone = Instantiate(mouse, spawnPoint.position, Quaternion.identity) as Rigidbody2D;
clone.velocity = new Vector3 (0, -1,0);
Do you have any idea why it's not working? Thank you again!
Sounds like you just need more practice program$$anonymous$$g. Clearly, setting velocity to -1 Y won't copy from the original (unless the original was also going at -1 Y.) And public variables holding the velocity are just just variables -- they aren't the actual velocity.