- Home /
The question is answered, right answer was accepted
Camera attached Error.
Hi, for everyone.
I need a help with an unexpected error that I found in my code.
The following is a peace of my code using in a component:
public class Shoot : MonoBehaviour { [SerializeField] private GameObject bulletPrefab; private GameObject _bullet; private Camera _camera; private float _yPlayerPos;
void Start()
{
_camera = GetComponent<Camera>();
_yPlayerPos = transform.position.y;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = _camera.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
//---- I cut the other part of the code because it is irrelevant for the error----
}
}
} As you can see in this peace of code avobe, I got the camera attached to this object to make some internal logic. This script is a componne that I added to my player object. I also attached the camera to the player object, as you can see in the following image: When I start the game, and press clic, the following error is showed:
I have not found a posible cause for this error, so I appreciate if someone knows the reason and help me with this.
@caceresanderson036 You probably have the Shoot script attached not to the camera, but the Player, which means it can't be found as it's nested one level down. So ins$$anonymous$$d of _camera = GetComponent<Camera>();
, try use _camera = Camera.main;
(or _camera = GetComponentInChildren<Camera>();
). When that works, consider reading up on the various GetComponent flavors: GetComponentInChildren, GetComponentInParent, GetComponentsInChildren and so on.
Answer by caceresanderson036 · Mar 11, 2020 at 08:12 PM
Hi @JPhilipp. That was the error. I am using Camera.main and it works perfectly.
Thaks for your help.
Follow this Question
Related Questions
Camera Problems, Deactivate Culling and strange Graphical Glitches in Editor 0 Answers
Error when player get's shot 1 Answer
'UniversalAdditionalCameraData' has been destroyed but you are still trying to access it. 1 Answer
There is no renderer attacked to main camera 2 Answers
Screen position out of view frustrum?? 0 Answers