Search Unity

Why is the shooting script attached to the camera?

Discussion in 'Getting Started' started by warrenbrandt, Jul 28, 2019.

  1. warrenbrandt

    warrenbrandt

    Joined:
    Mar 3, 2018
    Posts:
    413
    i watched a tutorial that got my character shooting

    but why was the script attached to the camera? shouldnt there be a separate object called playershoot or something where the script should be attached?

    i moved the script and set everything up but this line in my shooting script complains

    target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));

    its moaning about camera, i tried putting in the object name where the script is now sitting but it wont work as i suspected because this line is getting the borders of the screen via the camera, right?

    i was initially trying to destroy objects (the bullets) when they leave the screen and on my test it works, but when i try attach the code to my shooting script it was moaning about no rigidbody2d being available because the script is applied to a camera not a rigidbody2d ...how can i manage all this?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    That line of code converts the position of the mouse, on screen, to a 3D position in the world. To that you of course need a camera.

    So that's a decent reason to attach the script to the camera object; then you can get the camera simply via GetComponent<Camera>().

    If you want to put the script somewhere else, then you can instead change that bit to Camera.main, which is a reference to the main camera in the scene.
     
    Ryiah likes this.
  3. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,190
    Alternatively, if you have multiple cameras and the main camera isn't necessarily the player, you can create a public field for the class of type camera, assign the player camera to it in the Inspector, and then reference that field.

    Code (csharp):
    1. public Camera playerCamera;
    Code (csharp):
    1. target = playerCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
     
    JoeStrout likes this.