Hello. For a few deys straight i cant find a solution for this problem. I want to rotate and then shoot a bullet into mouse position. I tried using planes, camera.mian.screentoworldpoint but that dont work. I dont know what i am doing wrong. This is my code so far:
void Awake()
{
rb = bullet.AddComponent<Rigidbody2D>() as Rigidbody2D;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(mousePos);
Vector2 direction = new Vector2(
mousePos.x - Gracz1.transform.position.x,
mousePos.y - Gracz1.transform.position.y
);
Instantiate(bullet, Gracz1.transform.position, Quaternion.identity);
bullet.transform.LookAt(direction);
rb.velocity = new Vector2(direction.x, direction.y);
}
}
From this I get "object reference not set to an instance of object’ error and i dont know what to do with it. Bullet spawns but dont rotate and dont ‘shoot’ at mouse position. My camera is set to ortoghraphic.
It looks like you are trying to add a Rigidbody Component to your bullet prefab by calling AddComponent. It also looks like you are trying to store a reference to that Rigidbody in rb from the return of that call.
Unity will let you add a Component to a prefab from script, but once you do that one time, subsequent AddComponent calls will not return a value since your prefab already has that component.
So if your prefab already has a Rigidbody, this line will return null:
rb = bullet.AddComponent<Rigidbody2D>() as Rigidbody2D;
However, even if you did get a reference there, it wouldn’t be what you want. A reference to the Rigidbody from your bullet prefab would not do you any good since it is not the actual bullet you are Instantiating in the scene. The bullet prefab is just a template. You want a reference to the clone of the bullet prefab that you are Instantiating.
Instead of adding a Rigidbody to your prefab, you should make sure your prefab already has a Rigidbody added in the inspector and then call GetComponent after you instantiate an instance. Assign the return value of that call to rb and you will be good to go.
The quickest and dirtiest way to do that is like this: