- Home /
transform of instantiated bullet via ui button press not following the player
Problem: When a button is pressed, the bullet instantiates at the starting position of the bullet position that is a Child of my player even after the player moves. The shooting works just fine when I press spacebar to fire, but when I created a different function for UI button press the bulletposition's transform doesn't update. This is a snippet from my player script:
using UnityEngine;
using UnityEngine.UI;
public class PlayerControl : MonoBehaviour {
public GameObject PlayerBulletGO;
public GameObject bulletPosition;
public GameObject ExplosionPrefab;
public float FireRate;
private float canFire;
void Update () {
FireBullets();
}
// bulletPosition updates properly and works as intended
public void FireBullets()
{
// Fire bullets when spacebar is pressed
if(Input.GetButton("Jump") && canFire <= 0)
{
// Instantiate the bullet
GameObject bullet = (GameObject)Instantiate(PlayerBulletGO);
bullet.transform.position = bulletPosition.transform.position;
canFire = FireRate;
}
else
{
canFire -= Time.deltaTime;
}
}
// bulletPosition stay where player is instantiated at the start of the game
public void FireBulletsTouch()
{
// Fire bullets when spacebar is pressed
if(canFire <= 0)
{
// Instantiate the bullet
GameObject bullet = (GameObject)Instantiate(PlayerBulletGO);
bullet.transform.position = bulletPosition.transform.position;
canFire = FireRate;
}
else
{
canFire -= Time.deltaTime;
}
}
}
This is the whole script of the UI button for shooting.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonHold : MonoBehaviour {
public Button fireButton;
public PlayerControl playerShoot;
public bool isHeld;
void Update()
{
if(isHeld)
{
playerShoot.FireBulletsTouch();
}
}
public void OnPointerDown()
{
isHeld = true;
}
public void OnPointerUp()
{
isHeld = false;
}
}
I have tried various things such as the one without event trigger but with PointerEventData and all but the outcome is still the same. At first the script for UI button shooting was inside the PlayerControl script too but since I can't fix the problem and also the script is getting messier I decided to create a new script for the button which just gives the same outcome.
Also I would like to know a better way of making it possible for the player to shoot on normal button tap and while on hold. Please help me with this one. Thank you!
Your answer
Follow this Question
Related Questions
GameObject change Position after game started 1 Answer
transform.position on Instaniated object does not match inspector 0 Answers
How do I instantiate on the game object's position that i put the script on 1 Answer
Instanitiate PreFabs and let them move to different locations 1 Answer
Why can't I get the transform from an instantiated object? 1 Answer