Why is there no camera attached?

alright so I know that this has been asked a million and one times, but I cannot wrap my head around what is going on here. I have also tried a bunch of "solutions that I cannot get to work.

  1. public class LSMyShoot : MonoBehaviour

  2. {

  3. float Timer = 0f;

  4. public float Cooldown = 2f;

  5. public float ProjectileSpeed = 8.0f;

  6. private Vector3 target;

  7. public GameObject player;

  8. public GameObject ProjectilePrefab;

  9. public GameObject ProjectileStart;

  10. void FixedUpdate()

  11. {

  12.  target = transform.GetComponent().ScreenToWorldPoint(new  Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
    
  13.    Vector3 difference = target - player.transform.position; 
    
  14.   float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; 
    
  15. player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
    

You didn’t specify what type of component you want to get from transform in this line:

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

Also it is not optimal to use GetComponent() method in methods that are updated often like Update(), FixedUpdate(), LateUpdate() and couroutines because it takes time to find the component and produces garbage in memory which can cause lag spikes in game after some time when garbage collector collects it.

To avoid that sort of problem cache the component in class field and get it in method like Awake(), Start(), OnEnable() or other initialization methods.


If I’m not missing something, the code should look like this:

public class LSMyShoot : MonoBehaviour
{
    private new Camera camera;
    private float Timer = 0f;
    private Vector3 target;
    public float Cooldown = 2f;
    public float ProjectileSpeed = 8.0f;
    public GameObject player;
    public GameObject ProjectilePrefab;
    public GameObject ProjectileStart;

    void Awake()
    {
       camera = GetComponent<Camera>();
    }

    void FixedUpdate()
    {
       target = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
       Vector3 difference = target - player.transform.position; 
       float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
       player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
    }
}