Question by
haam · Jun 07, 2016 at 09:34 AM ·
c#unity 5instantiate prefab
Stuck With this codes.
public class Player : MonoBehaviour
{
public Vector2 jumpForce = new Vector2(0, 300);
public GameObject egg;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("space") || Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
if (Input.GetKeyDown(KeyCode.F))
{
GameObject shot = GameObject.Instantiate(egg, transform.position, transform.rotation) as GameObject;
}
}
}
}
what i am trying to achieve here is i want aa egg to drop directly from inside my player when ever i press a button, i am using an eggprefab to instantiate from inside the player but its not working ,can someone help me or guide to a right tutorial please c#.
Comment
Best Answer
Answer by UsmanAbbasi · Jun 07, 2016 at 09:58 AM
Because you have written the code to generate the egg using key "F" :
if (Input.GetKeyDown(KeyCode.F))
inside this if condition:
if (Input.GetKeyUp("space") || Input.GetMouseButtonDown(0))
so it will never work. You have to write conditions without nesting like this:
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("space") || Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
}
if (Input.GetKeyDown(KeyCode.F))
{
GameObject shot = GameObject.Instantiate(egg, transform.position, transform.rotation) as GameObject;
}
}
hahaha thank you i thought something is wrong with my code didnt even realise that