Parents Parent Question.

Hello all.

I did really search a lot of answers, but all of them did not help to me.

MAybe someone of you could help me.

I have a Player GameObject, which has a Camera and another Transform as Child.
I attached another Game object as Child of the additional Transform, and im trying to accsess the Camera from there.
But i dont get it right,.

Im trying this:

Camera View;
View = GetComponentInParent<Camera>();

int x = Screen.width / 2;
int y = Screen.height / 2;
Ray bullet = View.ScreenPointToRay(new Vector3(x, y, 0));

I always get Error

NullReferenceException: Object reference not set to an instance of an object
GunScript.Update () (at Assets/Assets/Scripts/GunScript.cs:37)

Can someone point me in the right direction?
It looks like i dont get the Camera as reference.

Greetings

Nin

Ok, found a sollution by myself, i now use

Ray bullet = GameObject.Find("Camera").GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y, 0));

It works.

Greetings

Nin

The camera isn’t a component of the parent object, but a component on the parents’ sibling object.

To access the camera you could use the following:

View = transform.root.GetComponentInChildren<Camera>();

Or if the View Camera is tagged as MainCamera you could use:

View = Camera.main;

Note that it would be more efficient to make the camera variable public and drag it into the inspector.

If it’s the only camera inside the scene and tagged as MainCamera, just use

View = Camera.main;

to set as a reference

The easiest solution is to create a public variable and drag-n-drop the camera into the field in the inspector

public Camera View;

111618-unbenannt.jpg

Camera is a Child of Player.

I think, as Camera is not a Parent of Gun or Attach Gun here, it will not be searched, as Camera is a child, and not a Component of Player.

Greetings

Nin