SchultzGames
Para tirar dúvidas, crie um tópico especifico na área "Dúvidas em Geral" e aguarde ser respondido. Evite comentar em tópicos não relacionados a sua dúvida :D
TÓPICOS RECENTES:
Tópico:
Postado em:
Postado por:
ShapeKeys do Blender para a Unity altera áreas próximas
COMO EVITAR QUE UM OBJETO (PLAYER,ITEM ETC...) ATRAVESSE UMA PAREDE.
Ajuda em Script de Verificação de Ação e Reação
unity Failed to load PlayerSettings (internal index #0). Most likely data f
modelar avatar e skins para um jogo web
PRECISO FAZER QUE MEU GAME FIQUE ONLINE
Materiais do Blander não aparecem no MeshRendere do Objeto na Unity
Repetiçoes de Textura no Terreno
SERVER IS DOWN - UNITY+MSQL
Procuro programadores - Novo jogo
Problema com o MS VEHICLES
Preciso de ajuda com a Unity
Problema com vídeo em 360° na Unity
Problemas no MS Vehicles
unity- eventos na Animação com Armature/Bones vinda do blender não funciona
ajuda exibir resultados simulados em uma liga Game Unity
Unity - ParticleSystem não é redirecionado no rawimage no canvas
Como resolver o problema de "face orientation" no Blender.
[DÚVIDA] Tive um problema com meu Canvas
erro na Directional Light
Problemas com o Directional Light da Unity 3D
210 Linhas de código para inimigo é muito grande?
Novo jogo da franquia Sphere game em desenvolvimento
malha da roda não girando com wheel collider unity
Problemas com ambiguidade
Touch mobile
INVALID TOKEN
Como acessar o "HD Render Pipeline" do HDRP por script?
CHAT GPT PRA JOGO DE TIRO? comentem
Tutorial script inimigo segue e foge do player
Ainda vale a pena lançar Asset na Asset Store?
Ajuda com tabela de historico de pontuaçao.
[TUTORIAL] Entrar no carro estilo GTA
Como derrapar um Whell Collider
Como altertar o valor do "Asymptote Value" do Whell Collider via Script
Preciso de ajuda para substituir valor de variavel em outro script
Ajuda com Top Down Shooter utilizando Photon
Duvida com Netcode
[RESOLVIDO] Unity - Movendo a Câmera na Horizontal/Vertical com Touch
Alguém me ajuda com os anúncios pfv
Segundo Trailer do jogo Dark Age, Feliz Natal a todos!
Unity - ScrollRect, Viewport, Content - O Conteúdo ñ inicia no topo
Coleta de itens
Unity - Cadastro do email do jogador
[GRATIS] PACK DE MODELOS 3D PARA JOGO DE TERROR
Onde Conseguir músicas para meu Jogo?
error CS0246 em Script
Alguem teve ja esse problema?
[Projeto em Andamento] Draug, um jogo de hordas
DISPONIVEL PARA FAZER MODELOS 3D
Unity-Loja.Como os Jogadores terão acesso aos ítens comprados na PlayStore?
Bugando depois do Build.
Primeiro Trailer do jogo Dark Age
Problema com sombra
Mesh e Material do objeto trocando para uma instancia no inicio do jogo
[RESOLVIDO] Unity - RawImages_Layer_Camera
INVESTIMENTO EM JOGOS E BANCO DE TALENTO
Teaser do meu novo projeto pessoal, Dark Age
Preciso de ajuda com mudança para mobile androide.
[RESOLVIDO] Posição final do objeto em jogo 2D
Input.GetAxis() obedercer a orientação de um objeto.
Interação com elementos UI
Meu primeiro jogo na steam
Minimap/Radar/GPS Estilo GTA V
[RESOLVIDO] Erro no console depois que formatei o pc
PACK GRÁTIS de Músicas ELETRÔNICAS para ajudar vocês em seus Jogos Indies!
[TUTORIAL] Entenda como funciona: ENUM, SWITCH, BREAK, CASE no C#
O Labirinto II - Baixe o Jogo
Qual e o codigo de Botões na unity para saber seus estados?
Como carregar itens pequenos dentro do carro sem que atravesse os colliders
[Duvida] Script pegar itens
Travamento ao trocar de cena
Colisão zoada e movimentação
Salvar objetos que foram destruidos entre cenas na unity
Quero começa a desenvolver um jogo de luta porem eu queria aprender a faze
Pegar qual objeto colidiu com o Linecast.
movimentação e camera?
[RESOLVIDO] Unity - SceneManager.LoadScene abre scene com objeto "vazio"
[RESOLVIDO] ajuda sobre skybox
MEU SIMULADOR DE CARRO
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY
[RESOLVIDO] Ausencia da funçao NavMesh na Unity 2022.2.12
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY - 2
Roll Up Um jogo de aventura e desáfios
Terminologia da Unity em outras engines
Como criar a iluminação do Sol no Sistema Solar?
Conexão de lobby pelo OnConnectedToMaster
Problema na exportção de projeto unity
[RESOLVIDO] Unity - Áudios estão emitindo som só Depois do Botão ser solto
Unity - Banco de Dados Online junto ao Jogo
Player virar para o inimigo(Prefab)
[TUTORIAL] Sistema De Save Game Ao Sair Da Fase
Problema de Sincronização de um objeto de um jogo multiplayer usa q Photon
Unity - Compartilhar meu Jogo
Alguém que manja do Google ADmob?
Unity - Avaliar meu Jogo
[RESOLVIDO] Destruir inimigo com o player.
Salvar e carregar dados na Unity de objetos prefabs sem sobrescrever os dad
Unity - Salvar os Dados do Jogador Online
Ontem à(s) 10:09 pm
Dom Mar 10, 2024 2:30 pm
Sex Mar 01, 2024 1:27 pm
Qui Fev 22, 2024 9:57 pm
Qua Fev 21, 2024 10:39 am
Ter Fev 20, 2024 9:28 am
Ter Fev 20, 2024 12:15 am
Seg Fev 19, 2024 1:06 pm
Seg Fev 12, 2024 1:56 pm
Seg Fev 12, 2024 1:17 pm
Dom Fev 11, 2024 8:55 pm
Dom Fev 11, 2024 11:16 am
Seg Fev 05, 2024 4:18 pm
Dom Fev 04, 2024 9:39 pm
Qua Jan 31, 2024 11:59 pm
Ter Jan 30, 2024 7:37 pm
Ter Jan 23, 2024 6:33 pm
Dom Jan 21, 2024 6:03 pm
Sáb Jan 20, 2024 7:03 pm
Sáb Jan 20, 2024 6:58 pm
Sáb Jan 20, 2024 6:39 pm
Sex Jan 19, 2024 1:29 pm
Sex Jan 19, 2024 8:40 am
Dom Jan 14, 2024 5:30 pm
Qua Jan 10, 2024 10:29 pm
Qua Jan 10, 2024 8:55 pm
Qua Jan 10, 2024 7:14 pm
Ter Jan 09, 2024 3:55 pm
Ter Jan 09, 2024 8:04 am
Sáb Jan 06, 2024 8:02 pm
Sex Jan 05, 2024 7:01 am
Sex Jan 05, 2024 12:12 am
Qui Jan 04, 2024 6:55 pm
Qui Jan 04, 2024 12:52 pm
Qui Jan 04, 2024 4:34 am
Ter Jan 02, 2024 11:48 pm
Dom Dez 31, 2023 7:25 pm
Qua Dez 27, 2023 5:44 pm
Qua Dez 27, 2023 3:08 pm
Sáb Dez 23, 2023 7:27 pm
Sáb Dez 23, 2023 5:06 pm
Qui Dez 21, 2023 8:10 pm
Seg Dez 18, 2023 2:04 pm
Sex Dez 15, 2023 5:11 pm
Qui Dez 14, 2023 9:13 pm
Qui Dez 14, 2023 2:47 pm
Qui Dez 14, 2023 1:48 pm
Qua Dez 13, 2023 8:58 pm
Ter Dez 12, 2023 2:32 pm
Seg Dez 11, 2023 1:53 pm
Qua Dez 06, 2023 8:13 pm
Sáb Dez 02, 2023 8:06 pm
Qui Nov 30, 2023 7:49 am
Seg Nov 27, 2023 1:35 am
Qua Nov 22, 2023 7:37 am
Qui Nov 09, 2023 1:22 pm
Seg Nov 06, 2023 11:59 am
Ter Out 31, 2023 9:53 am
Dom Out 29, 2023 8:05 pm
Dom Out 29, 2023 3:03 am
Sex Out 27, 2023 3:43 pm
Sex Out 27, 2023 3:28 pm
Qua Out 25, 2023 1:20 pm
Seg Out 23, 2023 10:34 am
Dom Out 22, 2023 6:55 pm
Qui Out 19, 2023 11:57 pm
Qui Out 19, 2023 6:39 pm
Ter Out 17, 2023 6:37 pm
Ter Out 17, 2023 6:18 pm
Seg Out 16, 2023 1:59 pm
Sáb Out 14, 2023 12:15 pm
Qua Out 11, 2023 6:07 pm
Seg Out 09, 2023 4:19 pm
Qua Out 04, 2023 12:12 pm
Qua Out 04, 2023 12:11 pm
Ter Out 03, 2023 9:18 pm
Ter Out 03, 2023 9:08 pm
Ter Out 03, 2023 6:05 pm
Ter Set 26, 2023 12:45 pm
Seg Set 25, 2023 9:02 pm
Seg Set 25, 2023 9:47 am
Sáb Set 23, 2023 2:10 pm
Sex Set 22, 2023 9:01 pm
Qui Set 21, 2023 11:04 am
Qua Set 20, 2023 4:40 pm
Qua Set 20, 2023 9:15 am
Dom Set 17, 2023 12:17 pm
Sex Set 15, 2023 7:24 pm
Sex Set 15, 2023 5:41 pm
Sex Set 15, 2023 4:28 pm
Sex Set 15, 2023 10:56 am
Sex Set 15, 2023 10:15 am
Seg Set 11, 2023 11:43 am
Seg Set 11, 2023 11:31 am
Sáb Set 09, 2023 4:53 pm
Sáb Set 09, 2023 1:44 pm
Ter Set 05, 2023 11:12 pm
Ter Set 05, 2023 3:12 pm
Seg Set 04, 2023 11:53 pm



































































































Unity 5: Object reference not set to an instance of an object

3 participantes

Ir para baixo

DÚVIDA Unity 5: Object reference not set to an instance of an object

Mensagem por ZeroTuhnder Dom Jun 10, 2018 5:55 pm

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??
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
ZeroTuhnder
Iniciante
Iniciante

Masculino PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras : Unity 5:  Object reference not set to an instance of an object WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Unity 5: Object reference not set to an instance of an object

Mensagem por NKKF Dom Jun 10, 2018 5:59 pm

Você adicionou "enemyHealth" ao script?
NKKF
NKKF
ProgramadorMaster

Masculino 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 : Unity 5:  Object reference not set to an instance of an object Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: Unity 5: Object reference not set to an instance of an object

Mensagem por ZeroTuhnder Dom Jun 10, 2018 6:02 pm

Sim (eu acho), quando eu fiz a referência na 10° linha e fiz ela resgatar esse componente na 19°
ZeroTuhnder
ZeroTuhnder
Iniciante
Iniciante

Masculino PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras : Unity 5:  Object reference not set to an instance of an object WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Unity 5: Object reference not set to an instance of an object

Mensagem por NKKF Dom Jun 10, 2018 6:13 pm

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
NKKF
ProgramadorMaster

Masculino 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 : Unity 5:  Object reference not set to an instance of an object Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: Unity 5: Object reference not set to an instance of an object

Mensagem por Phph09 Dom Jun 10, 2018 6:16 pm

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)
Phph09
Phph09
Profissional
Profissional

Masculino PONTOS : 3541
REPUTAÇÃO : 240
Idade : 18
Respeito as regras : Unity 5:  Object reference not set to an instance of an object WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Unity 5: Object reference not set to an instance of an object

Mensagem por ZeroTuhnder Dom Jun 10, 2018 6:21 pm

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...
ZeroTuhnder
ZeroTuhnder
Iniciante
Iniciante

Masculino PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras : Unity 5:  Object reference not set to an instance of an object WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: Unity 5: Object reference not set to an instance of an object

Mensagem por ZeroTuhnder Dom Jun 10, 2018 6:23 pm

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);
        }
    }
}
Script "Player Health
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
ZeroTuhnder
Iniciante
Iniciante

Masculino PONTOS : 2115
REPUTAÇÃO : 0
Idade : 21
Áreas de atuação : Somente estudo atualmente
Respeito as regras : Unity 5:  Object reference not set to an instance of an object WvDYdlf

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos