I am building a script that is attached to the root of a GameObject that has several layers of hierarchy.
I am using GameObject.Find(“name”) to get access to various components (I know this is not the fastest way, that’s another story).
I can then manipulate the components and everything works fine. I then create a new pre-fab and drag my ‘functioning’ game object onto the pre-fab.
Problem is, when I instance the pre-fab multiple times only one copy of it works; the rest don’t. I think it has to do with the way I am getting to the components, which is slow to start.
The script is mean to drive an 8-wheel vehicle. I have 8 wheel colliders and 8 physical wheels; the colliders are a couple of levels deep in the hierarchy, so are the wheels. See the attached picture of the two instances of the pre-fab. I modify the script variables by manipulating them on the Inspector; note one of them has the wheels turning but the other does not.
I have also attached a picture of the hierarchy of one of the two pre-fab instances.
Here’s the script
function FixedUpdate ()
{
var left1Coll_go = GameObject.Find(“CollLeft1”);
var left2Coll_go = GameObject.Find(“CollLeft2”);
var left3Coll_go = GameObject.Find(“CollLeft3”);
var left4Coll_go = GameObject.Find(“CollLeft4”);
var right1Coll_go = GameObject.Find(“CollRight1”);
var right2Coll_go = GameObject.Find(“CollRight2”);
var right3Coll_go = GameObject.Find(“CollRight3”);
var right4Coll_go = GameObject.Find(“CollRight4”);
var left1Wh_go = GameObject.Find(“WheelLeft1”);
var left2Wh_go = GameObject.Find(“WheelLeft2”);
var left3Wh_go = GameObject.Find(“WheelLeft3”);
var left4Wh_go = GameObject.Find(“WheelLeft4”);
var right1Wh_go = GameObject.Find(“WheelRight1”);
var right2Wh_go = GameObject.Find(“WheelRight2”);
var right3Wh_go = GameObject.Find(“WheelRight3”);
var right4Wh_go = GameObject.Find(“WheelRight4”);
//
// Steering
//
left1Coll_go.collider.steerAngle = Steer;
left2Coll_go.collider.steerAngle = 0.75 * Steer;
left3Coll_go.collider.steerAngle = -0.75 * Steer;
left4Coll_go.collider.steerAngle = -Steer;
right1Coll_go.collider.steerAngle = Steer;
right2Coll_go.collider.steerAngle = 0.75 * Steer;
right3Coll_go.collider.steerAngle = -0.75 * Steer;
right4Coll_go.collider.steerAngle = -Steer;
left1Wh_go.transform.localEulerAngles.y = Steer;
left2Wh_go.transform.localEulerAngles.y = Steer/2;
left3Wh_go.transform.localEulerAngles.y = -Steer/2;
left4Wh_go.transform.localEulerAngles.y = -Steer;
right1Wh_go.transform.localEulerAngles.y = Steer;
right2Wh_go.transform.localEulerAngles.y = Steer/2;
right3Wh_go.transform.localEulerAngles.y = -Steer/2;
right4Wh_go.transform.localEulerAngles.y = -Steer;
//
// Thrust
//
left1Coll_go.collider.motorTorque = Gas;
right1Coll_go.collider.motorTorque = Gas;
}