- Home /
Efficiently mimic movements of GameObject
I have a "Player" GameObject and then I have a script that creates a bunch (a lot) of GameObjects called PlayerSlave. Each PlayerSlave has this script attached:
var offset;
function Start() { var master = GameObject.Find("Player"); offset = master.transform.position - transform.position; }
function Update () { var master = GameObject.Find("Player"); transform.position = master.transform.position - offset; transform.rotation = master.transform.rotation; }
It sets the position to the master with the offset of how far it was from the master on initialization.
The player is a sphere and he is moved using left and right arrow keys, which apply torque.
Each slave consists only of the transform, the mesh, the renderer, and the script.
When I run it and there are a lot of PlayerSlaves, it gets pretty choppy. I'm wondering if there's anything I can do to fix that with how I'm achieving this effect. Is it because I'm setting the position and rotation instead of using like Translate, etc.?
Answer by DallonF · Jun 06, 2010 at 02:55 AM
May I ask why you're not simply parenting the "PlayerSlaves" to the master? If you do that, Unity will automatically move them along with the parent.
Wow. I guess I'm just not experienced enough to have known I could do that. Thanks a bunch.
Answer by Mike 3 · Jun 05, 2010 at 08:46 PM
One thing you could try is to cache the results of the calls, and use Transform references
using GameObject.Find frequently will slow things down a lot there is also a minimal benefit from not using transform, but using a stored variable of it (though as i said, it's minimal, so feel free to remove it for readability)
var offset; private var master : Transform; private var myTransform : Transform;
function Start() { master = GameObject.Find("Player").transform; myTransform = transform; offset = master.position - myTransform.position; }
function Update () { myTransform.position = master.position - offset; myTransform.rotation = master.rotation; }
Your answer
Follow this Question
Related Questions
How can I defer the recalculation of child transforms whilst modifying the parent transform? 0 Answers
Position and rotation of a game object acting wired 0 Answers
Problem with Instantiate 2D object to right position C# 1 Answer
postion scale and rotation greyed out and not working 1 Answer
How to rotate/position the child object independently of the parent? 3 Answers