Hi, i want my character to throw shurikens from his hand in the direction of mouse.
Now it just spawns and fall down without any force.
public GameObject starPrefab;
public Transform hand;
public Transform player;
public float speed;
void Update()
{
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 12);
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
if (Input.GetMouseButtonDown(1))
{
Instantiate(starPrefab, hand.transform.position, player.rotation);
starPrefab.GetComponent<Rigidbody>().AddForce((mousePos) * speed);
}
}
if I add ,starPrefab =" before Instantiate, It’s just spawning (clone), (clone)(clone),(clone)(clone)(clone) etc. and correctly adding force to the mouse. I wouldn’t have a problem with that if spawning stopped working when last (clone) is destroyed (simple timed self destroy script on the star prefab). So how do I add the force to this instantiated object?
Prefabs are the blueprint and Instantiate returns the instance created from the blueprint. Right now, you’re trying to add force to the prefab, which will have no effect. If you overwrite the starPrefab variable, you will then create copies of the instance in the scene, and when that instance is deleted, you won’t be able to create more.
Instead, assign the instance to a new variable:
var instance = Instantiate(starPrefab, hand.transform.position, player.rotation);
instance.GetComponent<Rigidbody>().AddForce((mousePos) * speed);
That works, kind of, finally spawning and throwing not just falling. No matter if character facing left or right, on right screen the force is as it should be, on left side the force is weaker.
Failed to upload video, so at least this: - Find & Share on GIPHY Not the best quality, but still can see what the problem is.
Edit: Problem solved as soon as I posted this reply. In the codevar instance = Instantiate(starPrefab, hand.transform.position, player.rotation);
I just added transform to the player.rotation
var instance = Instantiate(starPrefab, hand.transform.position, player.transform.rotation);
@Adrian i did this, but i got a compiler error saying that i don’t have rigidbody on my newly instantiated object, aka my bullet, and i don’t know how to get components onto the prefab. help?