- Home /
the player is not shooting
Hello,
I am trying to build a space shooter type of game, however my player does not shoot, probably because according to Unity, the laserPrefab is not being recognised (no value assigned).
Assets/Scripts/Player.cs(9,33): warning CS0649: Field 'Player.laserPrefab' is never assigned to, and will always have its default value null
Can someone please help me understand what is wrong with the script?
public class Player : MonoBehaviour {
[SerializeField] float moveSpeed = 10f; [SerializeField] float padding = 1f; [SerializeField] GameObject laserPrefab; [SerializeField] float projectileSpeed = 10f; [SerializeField] float projectileFiringPeriod = 0.1f;
Coroutine firingCoroutine; float xMin; float xMax; float yMin; float yMax; void Start() { SetUpMoveBoundaries();
} void Update() { Move(); Fire(); } private void Fire() { if (Input.GetButtonDown("Fire1")) { firingCoroutine = StartCoroutine(FireContinuously()); } if (Input.GetButtonUp("Fire1")) { StopCoroutine(firingCoroutine); } } IEnumerator FireContinuously() { while (true) { GameObject laser = Instantiate( laserPrefab, transform.position, Quaternion.identity) as GameObject; laser.GetComponent().velocity = new Vector2(0, projectileSpeed); yield return new WaitForSeconds(projectileFiringPeriod); } } private void Move() { var deltaX = Input.GetAxis("Horizontal") Time.deltaTime moveSpeed; var deltaY = Input.GetAxis("Vertical") Time.deltaTime moveSpeed; var newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax); var newYPos = Mathf.Clamp(transform.position.y + deltaY, yMin, yMax); transform.position = new Vector2(newXPos, newYPos); } private void SetUpMoveBoundaries() { Camera gameCamera = Camera.main; xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x + padding; xMax = gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x - padding; yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y + padding; yMax = gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y - padding; } }
THANK YOU SOOO MUCH!
hello.
edit the post. Apste the code using the Code sampler button
Answer by Zentiu · Mar 11, 2020 at 09:31 PM
Make sure you set the prefab in the inspector by draging the prefab into the laserprefab variable in the inspector. The error indicates that you made a variable of gameobject laserprefab but when you wish to call for it the game does not know what you mean becase you never assigned the prefab to that variable.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Function delay? 1 Answer
Distribute terrain in zones 3 Answers
Issue involving coroutines and animation 0 Answers