- Home /
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.
public class LSMyShoot : MonoBehaviour
{
float Timer = 0f;
public float Cooldown = 2f;
public float ProjectileSpeed = 8.0f;
private Vector3 target;
public GameObject player;
public GameObject ProjectilePrefab;
public GameObject ProjectileStart;
void FixedUpdate()
{
target = transform.GetComponent().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);
Answer by Sztormu · Oct 29, 2021 at 08:25 AM
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);
}
}