Unity 5: Object reference not set to an instance of an object
3 participantes
Página 1 de 1
Unity 5: Object reference not set to an instance of an object
Galera, sou novo nesse negocio de scripting em C# e eu estou fazendo uma das aulas padrões da Unity, mas eu me deparei com um erro que não consigo resolver, eu usei um código para fazer um inimigo ir até um jogador e ataca-lo, até ai tudo bem, mas quando eu fui testar deu o erro: NullReferenceException: Object reference not set to an instance of an object enemyMovement.Update () (at Assets/enemyMovement.cs:27)
quando eu digitei a linha: if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0) {
Alguém pode me ajudar??
quando eu digitei a linha: if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0) {
Alguém pode me ajudar??
- Código:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class enemyMovement : MonoBehaviour {
public Transform player; // Reference to the player's position.
PlayerHealth playerHealth; // Reference to the player's health.
EnemyHealth enemyHealth; // Reference to this enemy's health.
NavMeshAgent nav; // Reference to the nav mesh agent.
void Awake ()
{
// Set up the references.
player = GameObject.FindGameObjectWithTag ("Player").transform;
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent <EnemyHealth> ();
nav = GetComponent <UnityEngine.AI.NavMeshAgent> ();
}
void Update ()
{
// If the enemy and the player have health left...
if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0) {
// ... set the destination of the nav mesh agent to the player.
nav.SetDestination (player.position);
}
// Otherwise...
else {
// ... disable the nav mesh agent.
nav.enabled = false;
}
}
}
ZeroTuhnder- Iniciante
- PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras :
Re: Unity 5: Object reference not set to an instance of an object
Você adicionou "enemyHealth" ao script?
NKKF- ProgramadorMaster
- PONTOS : 4570
REPUTAÇÃO : 574
Idade : 19
Áreas de atuação : Desenvolvedor na Unity, NodeJS, React, ReactJS, React Native, MongoDB e Firebase.
Respeito as regras :
Re: Unity 5: Object reference not set to an instance of an object
Sim (eu acho), quando eu fiz a referência na 10° linha e fiz ela resgatar esse componente na 19°
ZeroTuhnder- Iniciante
- PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras :
Re: Unity 5: Object reference not set to an instance of an object
Só uma dúvida: Quando o inimigo ficar sem vida, ele morre, não é? Então por que você faz a verificação se ele está vivo ou não?
NKKF- ProgramadorMaster
- PONTOS : 4570
REPUTAÇÃO : 574
Idade : 19
Áreas de atuação : Desenvolvedor na Unity, NodeJS, React, ReactJS, React Native, MongoDB e Firebase.
Respeito as regras :
Re: Unity 5: Object reference not set to an instance of an object
O player tem a tag Player?
O player tem o script PlayerHealth?
O inimigo(objeto com esse script) tem o script EnemyHealth?
O inimigo(objeto com esse script) tem navmesh?
Faça a verificação
if(PlayerHealth != null && EnemyHealth != null)
O player tem o script PlayerHealth?
O inimigo(objeto com esse script) tem o script EnemyHealth?
O inimigo(objeto com esse script) tem navmesh?
Faça a verificação
if(PlayerHealth != null && EnemyHealth != null)
Phph09- Profissional
- PONTOS : 3541
REPUTAÇÃO : 240
Idade : 18
Respeito as regras :
Re: Unity 5: Object reference not set to an instance of an object
NKKF : Então, é porque se eu remover essa verificação (If e Else) aparece um outro erro quando eu inicio o jogo: "SetDestination" can only be called on an active agent that has been placed on a NavMesh.UnityEngine.AI.NavMeshAgent:SetDestination(Vector3) enemyMovement:Update() (at Assets/enemyMovement.cs:27)
Phph09: Sim, meu player tem a tag "Player" e o script "PlayerHealth" e esse inimigo tem NavMesh e o script "EnemyHealth" tudo está presente, por isso não sei qual é o erro...
Phph09: Sim, meu player tem a tag "Player" e o script "PlayerHealth" e esse inimigo tem NavMesh e o script "EnemyHealth" tudo está presente, por isso não sei qual é o erro...
ZeroTuhnder- Iniciante
- PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras :
Re: Unity 5: Object reference not set to an instance of an object
Script "EnemyHealth"
- Código:
using UnityEngine;
namespace CompleteProject
{
public class EnemyHealth : MonoBehaviour
{
public int startingHealth = 100; // The amount of health the enemy starts the game with.
public int currentHealth; // The current health the enemy has.
public float sinkSpeed = 2.5f; // The speed at which the enemy sinks through the floor when dead.
public int scoreValue = 10; // The amount added to the player's score when the enemy dies.
public AudioClip deathClip; // The sound to play when the enemy dies.
Animator anim; // Reference to the animator.
AudioSource enemyAudio; // Reference to the audio source.
ParticleSystem hitParticles; // Reference to the particle system that plays when the enemy is damaged.
CapsuleCollider capsuleCollider; // Reference to the capsule collider.
bool isDead; // Whether the enemy is dead.
bool isSinking; // Whether the enemy has started sinking through the floor.
void Awake ()
{
// Setting up the references.
anim = GetComponent <Animator> ();
enemyAudio = GetComponent <AudioSource> ();
hitParticles = GetComponentInChildren <ParticleSystem> ();
capsuleCollider = GetComponent <CapsuleCollider> ();
// Setting the current health when the enemy first spawns.
currentHealth = startingHealth;
}
void Update ()
{
// If the enemy should be sinking...
if(isSinking)
{
// ... move the enemy down by the sinkSpeed per second.
transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
}
}
public void TakeDamage (int amount, Vector3 hitPoint)
{
// If the enemy is dead...
if(isDead)
// ... no need to take damage so exit the function.
return;
// Play the hurt sound effect.
enemyAudio.Play ();
// Reduce the current health by the amount of damage sustained.
currentHealth -= amount;
// Set the position of the particle system to where the hit was sustained.
hitParticles.transform.position = hitPoint;
// And play the particles.
hitParticles.Play();
// If the current health is less than or equal to zero...
if(currentHealth <= 0)
{
// ... the enemy is dead.
Death ();
}
}
void Death ()
{
// The enemy is dead.
isDead = true;
// Turn the collider into a trigger so shots can pass through it.
capsuleCollider.isTrigger = true;
// Tell the animator that the enemy is dead.
anim.SetTrigger ("Dead");
// Change the audio clip of the audio source to the death clip and play it (this will stop the hurt clip playing).
enemyAudio.clip = deathClip;
enemyAudio.Play ();
}
public void StartSinking ()
{
// Find and disable the Nav Mesh Agent.
GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;
// Find the rigidbody component and make it kinematic (since we use Translate to sink the enemy).
GetComponent <Rigidbody> ().isKinematic = true;
// The enemy should no sink.
isSinking = true;
// Increase the score by the enemy's score value.
ScoreManager.score += scoreValue;
// After 2 seconds destory the enemy.
Destroy (gameObject, 2f);
}
}
}
- Código:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
namespace CompleteProject
{
public class PlayerHealth : MonoBehaviour
{
public int startingHealth = 100; // The amount of health the player starts the game with.
public int currentHealth; // The current health the player has.
public Slider healthSlider; // Reference to the UI's health bar.
public Image damageImage; // Reference to an image to flash on the screen on being hurt.
public AudioClip deathClip; // The audio clip to play when the player dies.
public float flashSpeed = 5f; // The speed the damageImage will fade at.
public Color flashColour = new Color(1f, 0f, 0f, 0.1f); // The colour the damageImage is set to, to flash.
Animator anim; // Reference to the Animator component.
AudioSource playerAudio; // Reference to the AudioSource component.
PlayerMovement playerMovement; // Reference to the player's movement.
PlayerShooting playerShooting; // Reference to the PlayerShooting script.
bool isDead; // Whether the player is dead.
bool damaged; // True when the player gets damaged.
void Awake ()
{
// Setting up the references.
anim = GetComponent <Animator> ();
playerAudio = GetComponent <AudioSource> ();
playerMovement = GetComponent <PlayerMovement> ();
playerShooting = GetComponentInChildren <PlayerShooting> ();
// Set the initial health of the player.
currentHealth = startingHealth;
}
void Update ()
{
// If the player has just been damaged...
if(damaged)
{
// ... set the colour of the damageImage to the flash colour.
damageImage.color = flashColour;
}
// Otherwise...
else
{
// ... transition the colour back to clear.
damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
}
// Reset the damaged flag.
damaged = false;
}
public void TakeDamage (int amount)
{
// Set the damaged flag so the screen will flash.
damaged = true;
// Reduce the current health by the damage amount.
currentHealth -= amount;
// Set the health bar's value to the current health.
healthSlider.value = currentHealth;
// Play the hurt sound effect.
playerAudio.Play ();
// If the player has lost all it's health and the death flag hasn't been set yet...
if(currentHealth <= 0 && !isDead)
{
// ... it should die.
Death ();
}
}
void Death ()
{
// Set the death flag so this function won't be called again.
isDead = true;
// Turn off any remaining shooting effects.
playerShooting.DisableEffects ();
// Tell the animator that the player is dead.
anim.SetTrigger ("Die");
// Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
playerAudio.clip = deathClip;
playerAudio.Play ();
// Turn off the movement and shooting scripts.
playerMovement.enabled = false;
playerShooting.enabled = false;
}
public void RestartLevel ()
{
// Reload the level that is currently loaded.
SceneManager.LoadScene (0);
}
}
}
ZeroTuhnder- Iniciante
- PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras :
Tópicos semelhantes
» NullReferenceException: Object reference not set to an instance
» Error NullReferenceException: Object reference not set to an instance of an object
» NullReferenceException Object reference not set to an instance of an object
» Null Reference Exception: Object reference not set to an instance of an object
» Object Pooling
» Error NullReferenceException: Object reference not set to an instance of an object
» NullReferenceException Object reference not set to an instance of an object
» Null Reference Exception: Object reference not set to an instance of an object
» Object Pooling
Página 1 de 1
Permissões neste sub-fórum
Não podes responder a tópicos