Hi again everyone. I have this problem that i dont understand. I have thi little script here checking around my scene, and i am attempting to have it add the weaponSocket to the camera as a child. But the problem is, it throws an null ref expception , and i cant see why.
function Awake(){
if(transform.Find("WeaponSocket")){
var ws : Transform = transform.Find("WeaponSocket");
ws.parent = transform.Find("Camera").transform;
}
}
In oder to step into this block , means that it must have found the transform, and yet when it gets to the ws.parent = transform, it throws the error. Just a lil oversight into the scene and objects at play here. I have a Player Object, that has a CameraSocket attached to it, when the Player is instantiated, the camera is assigned to the camera socket and, and the weaponSocket should than be childed to the camera socket. This is how i intend to keep the weapon moving in sync with the camera.
I realise there is prolly way more efficient methods to achieve what i am trying to here, but im not that good, and just learning, so at the moment , its the onlt way i can think of to achieve what i am wanting.
Ok , i think i solved it myself, it would appear that transform.Find will only find transform under the transform being searched from ? is this right. I swapped to GameObject.Find , and no problems.
The problem seems to be with transform.Find(“Camera”). Are you sure there is a GameObject named “Camera”? Is the GameObject a child of the GameObject that this script is attached to?
Also, transform.Find() returns a transform, so the .transform at the end is unnecessary.
I think using GameObject will search the whole scene, transform will search the hierarchy of children only.
What are you actually trying to do? Get the main camera? I think you can just get Camera.Main, but I’m not in a place to try it… Just have a camera tagged as the main camera and this will return it. No searching needed (still test for a null return value just to be safe! Always!)
Just for anyone else who might come read this. I made a mistake above. It would work to just do: if (weaponSocket)
but it is a really good idea to explicitly check for null rather than this boolean check:
if (weaponSocket != null)
I’m not sure what it is about .Net or C# that makes this more stable when stated explicitly, but I’ve been warned so I thought I would pass this on.