Hello all! I am new to Unity, but have been using C# for a little while now. I am having trouble instantiating new objects through code. To start let me explain what I am trying to do. I am trying to make a vehicle script in C# and at the point in which I need to make WheelColliders. I am storing everything in a simple data type (as a class for future functionality, but is basically a struct for now):
class WheelData
{
//var X = 0;
//var Y = -0.00000000373;
//var Z = 0.0025;
public double rotation = 0.0;
public WheelCollider coll ;
public Transform graphic ;
public double maxSteerAngle = 0.0;
public float lastSkidMark = -1;
public bool powered = false;
public bool handbraked = false;
public Quaternion originalRotation ;
};
I have comment placed where I am getting a null reference upon runtime. Here is my current interpretation of how to do what I want:
// Use this for initialization
void Start ()
{
// setup wheels
// allocate memory
wheels = new WheelData[4];
// initialize objects
for (int i = 0; i < 4; i++)
wheels[i] = new WheelData();
wheels[0].graphic = transform.Find("WheelFL");
wheels[1].graphic = transform.Find("WheelFR");
wheels[2].graphic = transform.Find("WheelBL");
wheels[3].graphic = transform.Find("WheelBR");
wheels[0].maxSteerAngle = 30.0;
wheels[1].maxSteerAngle = 30.0;
wheels[2].powered = true;
wheels[2].handbraked = true;
wheels[3].powered = true;
wheels[3].handbraked = true;
foreach(WheelData w in wheels)
{
if(w.graphic == null)
Debug.Log("You need to assign all four wheels for the car script!");
if(!w.graphic.transform.IsChildOf(transform))
Debug.Log("Wheels need to be children of the Object with the car script!");
w.originalRotation = w.graphic.localRotation;
// create colliders
WheelCollider colliderObject = new WheelCollider();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~Here I am getting Null Reference~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
colliderObject.transform.parent = transform;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~Here I am getting Null Reference~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
colliderObject.transform.position = w.graphic.position;
w.coll = colliderObject;
w.coll.suspensionDistance = suspensionDistance;
JointSpring js = new JointSpring();
js.spring = springs;
js.damper = dampers;
js.targetPosition = targetPosition;
w.coll.suspensionSpring = js;
w.coll.center = w.graphic.localPosition;
// no grip, as we simulate handling ourselves
WheelFrictionCurve noStiffnessFrictionCurve = new WheelFrictionCurve();
noStiffnessFrictionCurve.stiffness = 0;
w.coll.forwardFriction = noStiffnessFrictionCurve;
w.coll.sidewaysFriction = noStiffnessFrictionCurve;
w.coll.radius = wheelRadius;
}
// get wheel height (height forces are applied on)
wheelY = wheels[0].graphic.localPosition.y;
}
The line : colliderObject.transform.parent = transform;
seems be the problem, but I am not understanding what I have done wrong.
Any help would be appreciated.