Unity C#: я получаю исключение NullReferenceException и не знаю, как его исправить/улучшить [дубликат]C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Unity C#: я получаю исключение NullReferenceException и не знаю, как его исправить/улучшить [дубликат]

Сообщение Anonymous »

Я делаю простую игру-стрелялку на основе счета с 3D-графикой в ​​Unity. Большая часть основных функций работает, но у меня возникли проблемы с реализацией системы оценки, из-за которой возникает исключение NullReferenceException.
Чтобы помочь описать проблему, я вставил код игрока, основного врага и система подсчета очков в игре.

Код: Выделить всё

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Player : MonoBehaviour
{
// Variables set for the object;  links object to other objects within the project
[SerializeField] private float playerSpeed = 10;
[SerializeField] private GameObject bullet;
[SerializeField] private Transform bulletSpawn;
[SerializeField] private GameObject explosion;
[SerializeField] private GameObject restart;
private int playerScore;
private Score _score;

// Start is called before the first frame update
void Start()
{
_score = GameObject.Find("Score").GetComponent();
}

// Update is called once per frame
void Update()
{
// Variables for movement inputs
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
// Player's position is 'transformed' every frame
transform.position += new Vector3(horizontalInput * playerSpeed * Time.deltaTime, 0, verticalInput * playerSpeed * Time.deltaTime);

// Shoot input
if (Input.GetButtonDown("Jump"))
Instantiate(bullet, bulletSpawn.position, bulletSpawn.rotation);

// Quit game input
if (Input.GetButtonDown("Cancel"))
UnityEngine.SceneManagement.SceneManager.LoadScene("Title");
}

// Method for incrementing the player's score
public void ScoreUp(int points)
{
playerScore += points;
_score.applyScore(playerScore);
}

// Method for when this certain object collides with another
void OnTriggerEnter(Collider other)
{
// When the object collides with a tagged object "enemy"
if (other.CompareTag("Enemy"))
{
// Spawn two other game objects and destroy this one
Instantiate(explosion, transform.position, transform.rotation);
Instantiate(restart, transform.position, transform.rotation);
Destroy(gameObject);
}
}
}

Код: Выделить всё

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicEnemy : MonoBehaviour
{
[SerializeField] private float enemySpeed = 9;
[SerializeField] private float detonateTimer = 3;
[SerializeField] private float randomSpawn = 6;
[SerializeField] private GameObject explosion;
[SerializeField] private int scoreGain = 1;
private Player _player;

// Start is called before the first frame update
void Start()
{
// The object spawns at a random distance away from its spawn point
transform.position += new Vector3(Random.Range(randomSpawn, -randomSpawn), 0, 0);
_player = GameObject.Find("Player Cone").GetComponent
();
}

// Update is called once per frame
void Update()
{
// Enemy's position is 'transformed' according to game time
transform.position = transform.position - new Vector3(0, 0, enemySpeed * Time.deltaTime);
// A timer dictates the amount of time the enemy object remains spawned within the scene
detonateTimer -= Time.deltaTime;
if (detonateTimer 

Подробнее здесь: [url]https://stackoverflow.com/questions/78177140/unity-c-im-getting-a-nullreferenceexception-and-im-not-sure-how-to-fix-impro[/url]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»