I am trying to get bullets to fire from a parented position. In the Weapon.cs Awake() function I create 2 gunports, pass the parent transform and a Vector3 to offset the position from the parent. When I run the code I get the following error from GunPort.cs:
NullReferenceException
GunPort…ctor (UnityEngine.Transform _owner, Vector3 _offsetPosition) (at Assets/GunPort.cs:37)
Starfighter.Awake () (at Assets/Starfighter.cs:63)
This error points to where I set the transform.parent to the passed _owner.transform. I have done something similar with parenting a camera to physical object with success and I dont know why there is a problem with the way I have done it here. The _owner is not null as it suggests which I verified from using the statement Debug.Log(_owner.ToString());. Please excuse the Itallic text it is not intentional. The only difference is that my GunPort does not have a physical object, its invisible, as intended.
Weapon.cs:
void Awake () {
gunPort = GetComponent<GunPort>();
gunPorts = new GunPort[2];
gunPorts[0] = new GunPort(transform, new Vector3(-10, 0, 0));
gunPorts[1] = new GunPort(transform, new Vector3(10, 0, 0));
}
void CheckFiringPrimaryWeapon()
{
if(shipControls.IsFiringPrimary)
{
Bullet clone;
clone = Instantiate(bullet, gunPorts[0].Position, transform.rotation) as Bullet;
clone = Instantiate(bullet, gunPorts[1].Position, transform.rotation) as Bullet;
}
}
GunPort.cs:
public class GunPort : MonoBehaviour {
private Transform owner;
public Vector3 Position
{
get { return transform.position; }
}
public GunPort(Transform _owner, Vector3 _offsetPosition)
{
transform.parent = _owner.transform;
transform.localPosition =
(Vector3.right * _offsetPosition.x) +
(Vector3.up * _offsetPosition.y) +
(Vector3.forward * _offsetPosition.z);
}
}