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:
Onde Conseguir músicas para meu Jogo?
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
Coleta de itens
Mesh e Material do objeto trocando para uma instancia no inicio do jogo
Unity - Cadastro do email do jogador
[RESOLVIDO] Unity - RawImages_Layer_Camera
INVESTIMENTO EM JOGOS E BANCO DE TALENTO
Alguém me ajuda com os anúncios pfv
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"
CHAT GPT PRA JOGO DE TIRO? comentem
[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
ajuda com o sistema de drag and drop com controle no invetario
Como executar outros blocos fora do bloco static void Main()
Usando a biblioteca UnityEngine fora da Unity
Mixamo - Character Gratuito?
Touch mobile
Erro NullReferenceException Não consigo resolver
Criador de Sites Freelancer DISPONIVEL!!!
Unity - Não deixar o Jogador alterar o Jogo pelo regedit do pc?
Tiro com Botao UI (ME AJUDEM)
[Projeto em Andamento] Draug, um jogo de hordas
Vagas de programadores e modeladores para startup
Consigo herdar/ copiar parâmetros do animator da unity?
O que seriam os códigos-fonte?
[RESOLVIDO] Unity Vulkan - Out of memory! (allocating memory for image)
Unity Problema de Vírus
[TUTORIAL] Como fazer uma gota de água na Unity
Mirror ou Photon Pun 2 ??? para Mobile
Character Player Modular
Icones não aparecem na Interface da Unity
Verificar se player está posado em blogo
Logica para criar (Player, Inventario, Arma) - Mobile
Sistema de pegar passageiros
Trailer Final de O Labirinto II
Meu jogo não conecta no google play games
ALGUEM ME AJUDA PFV
Problema tentando inserir "Sprite"
Oferto Serviço Programação para Jogos
FAZER AÇÂO AO ENTRAR NO CAMPO DA CAMERA
[RESOLVIDO] QUEBRA DE LINHA NO PLACEHOLDER. Nao lembro como que faz
Unity - Qual o Limite Máximo de Linhas em um Script para q ele fique Leve?
movimento 2d
Alguém que ja publicou na steam pode me ajudar com isso?
Animação Unity toda bugada
UDaySurvival - Jogo de sobrevivência de mundo aberto para mobile!https://yo
Trailer do meu jogo O Labirinto II
Jogo Atisk (Trailer)
Adicionem meu jogo na lista de desejos
Discord!
Como executar a void de um outro scrypt
Shader não funciona no Unity URP
Jogo Mobile - Ultimate Flight Simulator - Real World SDK
Unity - FPS e CPU ???
Usar microfone na Unity
Jogo ficando escuro quando faço a Build pela cena menu
Dúvida sobre movimentação do personagem
Ontem à(s) 6:16 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 10:55 am
Qua Nov 22, 2023 7:37 am
Qua Nov 15, 2023 2:21 pm
Qui Nov 09, 2023 1:22 pm
Seg Nov 06, 2023 11:59 am
Sáb Nov 04, 2023 5:54 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
Seg Out 02, 2023 10:39 am
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
Dom Set 03, 2023 9:47 pm
Sáb Set 02, 2023 11:53 am
Sex Set 01, 2023 2:21 pm
Qui Ago 31, 2023 8:19 pm
Qui Ago 31, 2023 6:15 pm
Qua Ago 30, 2023 11:21 am
Ter Ago 29, 2023 8:43 pm
Seg Ago 28, 2023 7:18 pm
Sáb Ago 26, 2023 4:49 pm
Sáb Ago 26, 2023 4:38 pm
Qui Ago 17, 2023 1:56 am
Qua Ago 16, 2023 10:21 pm
Seg Ago 14, 2023 12:28 pm
Dom Ago 06, 2023 5:24 pm
Dom Ago 06, 2023 10:58 am
Qui Ago 03, 2023 9:38 am
Qua Ago 02, 2023 8:20 am
Ter Ago 01, 2023 6:07 pm
Dom Jul 30, 2023 5:43 pm
Sáb Jul 29, 2023 7:24 pm
Qui Jul 27, 2023 9:27 am
Seg Jul 24, 2023 11:12 am
Seg Jul 24, 2023 12:44 am
Seg Jul 24, 2023 12:37 am
Seg Jul 24, 2023 12:17 am
Seg Jul 24, 2023 12:10 am
Qua Jul 19, 2023 11:37 am
Ter Jul 18, 2023 7:12 pm
Qua Jul 12, 2023 9:49 am
Ter Jul 11, 2023 8:58 am
Ter Jul 11, 2023 1:03 am
Seg Jul 10, 2023 9:10 pm
Sex Jul 07, 2023 4:14 pm
Ter Jul 04, 2023 12:11 am
Sex Jun 30, 2023 8:10 pm
Qui Jun 29, 2023 5:19 pm
Qui Jun 29, 2023 3:40 pm
Ter Jun 27, 2023 1:45 am
Seg Jun 19, 2023 11:03 am
Dom Jun 18, 2023 6:11 pm
Dom Jun 04, 2023 2:41 pm
Ter maio 30, 2023 7:28 pm
Ter maio 30, 2023 6:04 am
Seg maio 29, 2023 7:53 pm
Sáb maio 27, 2023 3:11 pm



































































































NullReferenceException: Object reference not set to an instance

4 participantes

Ir para baixo

DÚVIDA NullReferenceException: Object reference not set to an instance

Mensagem por gamedevretro Qui Fev 09, 2023 10:26 am

preciso de ajuda. Estava criando a AI no unity, e simplesmente não funciona nenhuma das animações, e o AI fica dentro do chão (andando)
e diz, que tem um objecto de referencia não setado, mas eu não sei qual, me ajudem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy1 : MonoBehaviour
{
    public int rutina;
    public float cronometro;
    public Animator ani;
    public Quaternion angulo;
    public float grado;


    // Start is called before the first frame update
    void Start()
    {
        ani = GetComponent<Animator>();    
    }

    // Update is called once per frame
    public void Comportamiento_Enemy()
    {
        cronometro += 1 * Time.deltaTime;
        if (cronometro >= 4)
        {
            rutina = Random.Range(0, 2);
            cronometro = 0;
        }
        switch (rutina)
        {
            case 0:
                ani.SetBool("walk", false);
                break;
            case 1:
                grado = Random.Range(0, 360);
                angulo = Quaternion.Euler(0, grado, 0);
                rutina++;
                break;

            case 2:
                transform.rotation = Quaternion.RotateTowards(transform.rotation, angulo, 0.5f);
                transform.Translate(Vector3.forward * 1 * Time.deltaTime);
                ani.SetBool("walk", true);
                break;
        }
    }

    void Update()
    {
        Comportamiento_Enemy();
    }
}

gamedevretro
Iniciante
Iniciante

PONTOS : 309
REPUTAÇÃO : 0
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por MadCow Qui Fev 09, 2023 12:37 pm

Olá amigo eu tenho uma AI simples para inimigos que funciona bem, é boa para inimigos tipo corpo a corpo, mais vc pode adicionar projetos sem problemas.

Fiz um pequeno vídeo de como utilizar o script ok, sempre verifica se vc esta usando Humanoides e se os parâmetros do Animator estão corretos e a conexão com as animações.

Este Script possui alguns Eventos para vc complementar com outros scripts ou dar mais vida ao Inimigo como Sons, Efeitos, etc.

Código:
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;

public class InimigoAI : MonoBehaviour
{

    public NavMeshAgent agent;

    [SerializeField] string PlayerTag = "Player";
    Transform player;

    public LayerMask whatIsGround, whatIsPlayer;

    [SerializeField] float vidaInimigo;

    //Patrulhamento
    public Vector3 walkPoint;
    bool walkPointSet;
    [SerializeField] float pontoCaminhada;

    //Atacante
    [SerializeField] float tempoEntreAtaques;
    bool PlayerAtacado;

    //Estados
    public float gamaVisao, raioAtaque;
    public bool playerNaVisao, playerNoAlcanceAtaque;

    public Animator anim;

    public UnityEvent EventoInicio;
    public UnityEvent EventoAtaque;
    public UnityEvent EventoPatrulhamento;
    public UnityEvent EventoBuscaPlayer;
    public UnityEvent EventoMorte;

    private void Start()
    {
        if (EventoInicio == null)
            EventoInicio = new UnityEvent();

        if (EventoAtaque == null)
            EventoAtaque = new UnityEvent();

        if (EventoPatrulhamento == null)
            EventoPatrulhamento = new UnityEvent();

        if (EventoBuscaPlayer == null)
            EventoBuscaPlayer = new UnityEvent();

        if (EventoMorte == null)
            EventoMorte = new UnityEvent();

        player = GameObject.FindWithTag(PlayerTag).transform;
        anim.SetBool("Idle", true);
    }

    private void Awake()
    {
        player = GameObject.FindWithTag(PlayerTag).transform;
        agent = GetComponent<NavMeshAgent>();
        EventoInicio.Invoke();
    }

    private void Update()
    {

        playerNaVisao = Physics.CheckSphere(transform.position, gamaVisao, whatIsPlayer);
        playerNoAlcanceAtaque = Physics.CheckSphere(transform.position, raioAtaque, whatIsPlayer);

        if (!playerNaVisao && !playerNoAlcanceAtaque) Patrulhamento();
        if (playerNaVisao && !playerNoAlcanceAtaque) BuscandoPlayer();
        if (playerNoAlcanceAtaque && playerNaVisao) AttackPlayer();
    }

    private void Patrulhamento()
    {
        if (!walkPointSet) GerarPontoCaminho();

        if (walkPointSet)
            agent.SetDestination(walkPoint);

        Vector3 distanceToWalkPoint = transform.position - walkPoint;
        EventoPatrulhamento.Invoke();

        if (distanceToWalkPoint.magnitude < 1f)
            walkPointSet = false;
    }

    private void GerarPontoCaminho()
    {

        float randomZ = Random.Range(-pontoCaminhada, pontoCaminhada);
        float randomX = Random.Range(-pontoCaminhada, pontoCaminhada);

        walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", true);

        if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
            walkPointSet = true;
    }

    private void BuscandoPlayer()
    {
        agent.SetDestination(player.position);
        EventoBuscaPlayer.Invoke();
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", true);
    }

    private void AttackPlayer()
    {

        agent.SetDestination(transform.position);
        anim.SetBool("Idle", false);
        transform.LookAt(player);

        if (!PlayerAtacado)
        {
            ///CODIGO DO ATAQUE
            anim.SetBool("Walk", false);
            anim.SetBool("Attack", true);
            EventoAtaque.Invoke();

            PlayerAtacado = true;
            Invoke(nameof(ResetAtque), tempoEntreAtaques);
        } else
        {
            anim.SetBool("Walk", true);
        }
    }

    private void ResetAtque()
    {
        PlayerAtacado = false;
    }

    public void DanoNoInimigo(int damage)
    {
        vidaInimigo -= damage;
        anim.SetBool("Hit", true);
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", false);
        if (vidaInimigo <= 0) Invoke(nameof(InimigoMorreu), 0.5f);
    }
    private void InimigoMorreu()
    {
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Death", true);
        EventoMorte.Invoke();
    }


    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, raioAtaque);
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, gamaVisao);
    }

}

MadCow
MadCow
Iniciante
Iniciante

Masculino PONTOS : 1866
REPUTAÇÃO : 7
Idade : 36
Áreas de atuação : Sou programador a 20 Anos e a 8 anos trabalho com desenvolvimento de Jogos utilizando Unity
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

https://gbxgamers.com

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por gamedevretro Qui Fev 09, 2023 4:33 pm

MadCow escreveu:Olá amigo eu tenho uma AI simples para inimigos que funciona bem, é boa para inimigos tipo corpo a corpo, mais vc pode adicionar projetos sem problemas.

Fiz um pequeno vídeo de como utilizar o script ok, sempre verifica se vc esta usando Humanoides e se os parâmetros do Animator estão corretos e a conexão com as animações.

Este Script possui alguns Eventos para vc complementar com outros scripts ou dar mais vida ao Inimigo como Sons, Efeitos, etc.

Código:
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;

public class InimigoAI : MonoBehaviour
{

    public NavMeshAgent agent;

    [SerializeField] string PlayerTag = "Player";
    Transform player;

    public LayerMask whatIsGround, whatIsPlayer;

    [SerializeField] float vidaInimigo;

    //Patrulhamento
    public Vector3 walkPoint;
    bool walkPointSet;
    [SerializeField] float pontoCaminhada;

    //Atacante
    [SerializeField] float tempoEntreAtaques;
    bool PlayerAtacado;

    //Estados
    public float gamaVisao, raioAtaque;
    public bool playerNaVisao, playerNoAlcanceAtaque;

    public Animator anim;

    public UnityEvent EventoInicio;
    public UnityEvent EventoAtaque;
    public UnityEvent EventoPatrulhamento;
    public UnityEvent EventoBuscaPlayer;
    public UnityEvent EventoMorte;

    private void Start()
    {
        if (EventoInicio == null)
            EventoInicio = new UnityEvent();

        if (EventoAtaque == null)
            EventoAtaque = new UnityEvent();

        if (EventoPatrulhamento == null)
            EventoPatrulhamento = new UnityEvent();

        if (EventoBuscaPlayer == null)
            EventoBuscaPlayer = new UnityEvent();

        if (EventoMorte == null)
            EventoMorte = new UnityEvent();

        player = GameObject.FindWithTag(PlayerTag).transform;
        anim.SetBool("Idle", true);
    }

    private void Awake()
    {
        player = GameObject.FindWithTag(PlayerTag).transform;
        agent = GetComponent<NavMeshAgent>();
        EventoInicio.Invoke();
    }

    private void Update()
    {

        playerNaVisao = Physics.CheckSphere(transform.position, gamaVisao, whatIsPlayer);
        playerNoAlcanceAtaque = Physics.CheckSphere(transform.position, raioAtaque, whatIsPlayer);

        if (!playerNaVisao && !playerNoAlcanceAtaque) Patrulhamento();
        if (playerNaVisao && !playerNoAlcanceAtaque) BuscandoPlayer();
        if (playerNoAlcanceAtaque && playerNaVisao) AttackPlayer();
    }

    private void Patrulhamento()
    {
        if (!walkPointSet) GerarPontoCaminho();

        if (walkPointSet)
            agent.SetDestination(walkPoint);

        Vector3 distanceToWalkPoint = transform.position - walkPoint;
        EventoPatrulhamento.Invoke();

        if (distanceToWalkPoint.magnitude < 1f)
            walkPointSet = false;
    }

    private void GerarPontoCaminho()
    {

        float randomZ = Random.Range(-pontoCaminhada, pontoCaminhada);
        float randomX = Random.Range(-pontoCaminhada, pontoCaminhada);

        walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", true);

        if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
            walkPointSet = true;
    }

    private void BuscandoPlayer()
    {
        agent.SetDestination(player.position);
        EventoBuscaPlayer.Invoke();
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", true);
    }

    private void AttackPlayer()
    {

        agent.SetDestination(transform.position);
        anim.SetBool("Idle", false);
        transform.LookAt(player);

        if (!PlayerAtacado)
        {
            ///CODIGO DO ATAQUE
            anim.SetBool("Walk", false);
            anim.SetBool("Attack", true);
            EventoAtaque.Invoke();

            PlayerAtacado = true;
            Invoke(nameof(ResetAtque), tempoEntreAtaques);
        } else
        {
            anim.SetBool("Walk", true);
        }
    }

    private void ResetAtque()
    {
        PlayerAtacado = false;
    }

    public void DanoNoInimigo(int damage)
    {
        vidaInimigo -= damage;
        anim.SetBool("Hit", true);
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", false);
        if (vidaInimigo <= 0) Invoke(nameof(InimigoMorreu), 0.5f);
    }
    private void InimigoMorreu()
    {
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Death", true);
        EventoMorte.Invoke();
    }


    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, raioAtaque);
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, gamaVisao);
    }

}

obrigado amigo, eu vou testar aqui, qualquer coisa eu lhe informo. Vou seguir o video de exemplo.

gamedevretro
Iniciante
Iniciante

PONTOS : 309
REPUTAÇÃO : 0
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por gamedevretro Qui Fev 09, 2023 5:31 pm

Funcionou!!! As animações funcionaram.
Mas... a animação "Idle" não funciona, ela não inicia, e nem volta após um ataque, e a animação "walk" também. Ah, e AI entra no chão quando o player emburra ele...

Erro: Parameter 'Idle' does not exist.
UnityEngine.Animator:SetBool (string,bool)
InimigoAI:AttackPlayer () (at Assets/Scripts/InimigoAI.cs:121)
InimigoAI:Update () (at Assets/Scripts/InimigoAI.cs:76)

gamedevretro
Iniciante
Iniciante

PONTOS : 309
REPUTAÇÃO : 0
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por BlesseD Qui Fev 09, 2023 7:30 pm

gamedevretro escreveu:Funcionou!!! As animações funcionaram.
Mas... a animação "Idle" não funciona, ela não inicia, e nem volta após um ataque, e a animação "walk" também. Ah, e AI entra no chão quando o player emburra ele...

Erro: Parameter 'Idle' does not exist.
UnityEngine.Animator:SetBool (string,bool)
InimigoAI:AttackPlayer () (at Assets/Scripts/InimigoAI.cs:121)
InimigoAI:Update () (at Assets/Scripts/InimigoAI.cs:76)
É preciso adicionar um parâmetro do tipo Bool com o nome "Idle" no seu animator para a animação funcionar.
BlesseD
BlesseD
Desenvolvedor

Masculino PONTOS : 1726
REPUTAÇÃO : 29
Idade : 23
Áreas de atuação : 》Unity3D
》Criador de Games Independentes
》C# [Intermediário] / Designer Gráfico
》Jogos de Terror
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

https://store.steampowered.com/search/?developer=Samuka%20Gomes

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por gamedevretro Qui Fev 09, 2023 8:31 pm

BlesseD escreveu:
gamedevretro escreveu:Funcionou!!! As animações funcionaram.
Mas... a animação "Idle" não funciona, ela não inicia, e nem volta após um ataque, e a animação "walk" também. Ah, e AI entra no chão quando o player emburra ele...

Erro: Parameter 'Idle' does not exist.
UnityEngine.Animator:SetBool (string,bool)
InimigoAI:AttackPlayer () (at Assets/Scripts/InimigoAI.cs:121)
InimigoAI:Update () (at Assets/Scripts/InimigoAI.cs:76)
É preciso adicionar um parâmetro do tipo Bool com o nome "Idle" no seu animator para a animação funcionar.
eu coloquei, mas não funcionou, foi a primeira coisa que fiz.

gamedevretro
Iniciante
Iniciante

PONTOS : 309
REPUTAÇÃO : 0
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por MadCow Qui Fev 09, 2023 9:37 pm

Olá verifica os parâmetros das animações são 5 Bool, Idle, Attack, Walk, Hit, Death

Para modificar o erro do Inimigo entrar no chão basta remover o transform.LookAt(player); em AttackPlayer() e por um Quaternion.

Código Atualizado;

Código:
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;

[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(NavMeshAgent))]
public class InimigoAI : MonoBehaviour
{

    public NavMeshAgent agent;
    public Animator anim;

    [SerializeField] string PlayerTag = "Player";
    Transform player;

    [Header("Layers do Piso")]
    public LayerMask whatIsGround;
    [Header("Layers do Player")]
    public LayerMask whatIsPlayer;

    [Space]
    [SerializeField] float vidaInimigo;
    [SerializeField] float velocidadeRotar;
    [SerializeField] float pontoCaminhada;
    [SerializeField] float tempoEntreAtaques;

    [Range(0.2f, 1f)]
    [SerializeField] float VolumeAudio = 0.7f;

    bool PlayerAtacado;
    //Patrulhamento
    [Space]
    public Vector3 walkPoint;
    bool walkPointSet;
    

    //Estados
    public float gamaVisao, raioAtaque;
    public bool playerNaVisao, playerNoAlcanceAtaque;

    [Space]
    [Header("Eventos")]
    public UnityEvent EventoInicio;
    public UnityEvent EventoAtaque;
    public UnityEvent EventoPatrulhamento;
    public UnityEvent EventoBuscaPlayer;
    public UnityEvent EventoMorte;

    //ADICIONAR
    private Quaternion _lookVisaoRotate;
    private Vector3 _direcao;
    private AudioSource audioSource;

    AnimatorClipInfo[] m_CurrentClipInfo;

    private void Start()
    {
        if (EventoInicio == null)
            EventoInicio = new UnityEvent();

        if (EventoAtaque == null)
            EventoAtaque = new UnityEvent();

        if (EventoPatrulhamento == null)
            EventoPatrulhamento = new UnityEvent();

        if (EventoBuscaPlayer == null)
            EventoBuscaPlayer = new UnityEvent();

        if (EventoMorte == null)
            EventoMorte = new UnityEvent();

        player = GameObject.FindWithTag(PlayerTag).transform;
        anim.SetBool("Idle", true);

    }

    private void Awake()
    {
        player = GameObject.FindWithTag(PlayerTag).transform;
        agent = GetComponent<NavMeshAgent>();
        EventoInicio.Invoke();
    }

    private void Update()
    {

        playerNaVisao = Physics.CheckSphere(transform.position, gamaVisao, whatIsPlayer);
        playerNoAlcanceAtaque = Physics.CheckSphere(transform.position, raioAtaque, whatIsPlayer);

        if (!playerNaVisao && !playerNoAlcanceAtaque) Patrulhamento();
        if (playerNaVisao && !playerNoAlcanceAtaque) BuscandoPlayer();
        if (playerNoAlcanceAtaque && playerNaVisao) AttackPlayer();
    }

    
    private void Patrulhamento()
    {
        if (!walkPointSet) GerarPontoCaminho();

        if (walkPointSet)
            agent.SetDestination(walkPoint);

        Vector3 distanceToWalkPoint = transform.position - walkPoint;
        EventoPatrulhamento.Invoke();

        if (distanceToWalkPoint.magnitude < 1f)
            walkPointSet = false;
    }

    private void GerarPontoCaminho()
    {

        float randomZ = Random.Range(-pontoCaminhada, pontoCaminhada);
        float randomX = Random.Range(-pontoCaminhada, pontoCaminhada);

        walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", true);

        if (Physics.Raycast(walkPoint, -transform.up, 2f, whatIsGround))
            walkPointSet = true;
    }

    private void BuscandoPlayer()
    {
        agent.SetDestination(player.position);
        EventoBuscaPlayer.Invoke();
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", true);
    }

    
    private void AttackPlayer()
    {

        agent.SetDestination(transform.position);
        anim.SetBool("Idle", false);
        //transform.LookAt(player); // COMENTAR

        //ADICIONAR
        _direcao = (player.position - transform.position).normalized;
        _lookVisaoRotate = Quaternion.LookRotation(_direcao);
        transform.rotation = Quaternion.Slerp(transform.rotation, _lookVisaoRotate, Time.deltaTime * velocidadeRotar);
        //FIM ADICIONAR

        if (!PlayerAtacado)
        {
            ///CODIGO DO ATAQUE
            anim.SetBool("Walk", false);
            anim.SetBool("Attack", true);
            EventoAtaque.Invoke();
            PlayerAtacado = true;
            Invoke(nameof(ResetAtque), tempoEntreAtaques);
        } else
        {
            anim.SetBool("Walk", true);
        }
    }



    private void ResetAtque()
    {
        PlayerAtacado = false;
    }

    public void DanoNoInimigo(int damage)
    {
        vidaInimigo -= damage;
        anim.SetBool("Hit", true);
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Walk", false);
        if (vidaInimigo <= 0) Invoke(nameof(InimigoMorreu), 0.5f);
    }
    private void InimigoMorreu()
    {
        anim.SetBool("Attack", false);
        anim.SetBool("Idle", false);
        anim.SetBool("Death", true);
        EventoMorte.Invoke();
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, raioAtaque);
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, gamaVisao);
    }

}
MadCow
MadCow
Iniciante
Iniciante

Masculino PONTOS : 1866
REPUTAÇÃO : 7
Idade : 36
Áreas de atuação : Sou programador a 20 Anos e a 8 anos trabalho com desenvolvimento de Jogos utilizando Unity
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

https://gbxgamers.com

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por gamedevretro Sex Fev 10, 2023 11:22 am

funcionou! muito obrigado, nem sei como agradecer.

gamedevretro
Iniciante
Iniciante

PONTOS : 309
REPUTAÇÃO : 0
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por DarknessShark Sex Fev 10, 2023 11:28 am

eu testei, e funciona, mas, no meu ele não anda, tipo. Ele simplesmente só se desloca, mas não efetua a animação de "Walk" e, também o "Idle" não efetua, ele não começa com o "idle" e não troca após atacar ou quando para.
Eu já verifiquei os bool, e os nomes das animação, e o ataque funciona certinho. É só esses dois que não funcionam bem...
DarknessShark
DarknessShark
Iniciante
Iniciante

Masculino PONTOS : 745
REPUTAÇÃO : 5
Idade : 16
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por MadCow Sex Fev 10, 2023 8:17 pm

DarknessShark escreveu:eu testei, e funciona, mas, no meu ele não anda, tipo. Ele simplesmente só se desloca, mas não efetua a animação de "Walk" e, também o "Idle" não efetua, ele não começa com o "idle" e não troca após atacar ou quando para.
Eu já verifiquei os bool, e os nomes das animação, e o ataque funciona certinho. É só esses dois que não funcionam bem...

Olá suas animações Walk e Idle estão marcadas como Loop ?
MadCow
MadCow
Iniciante
Iniciante

Masculino PONTOS : 1866
REPUTAÇÃO : 7
Idade : 36
Áreas de atuação : Sou programador a 20 Anos e a 8 anos trabalho com desenvolvimento de Jogos utilizando Unity
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

https://gbxgamers.com

Ir para o topo Ir para baixo

DÚVIDA Re: NullReferenceException: Object reference not set to an instance

Mensagem por MadCow Sex Fev 10, 2023 8:18 pm

gamedevretro escreveu:funcionou! muito obrigado, nem sei como agradecer.

Por nada, se precisar de ajuda so chamar
MadCow
MadCow
Iniciante
Iniciante

Masculino PONTOS : 1866
REPUTAÇÃO : 7
Idade : 36
Áreas de atuação : Sou programador a 20 Anos e a 8 anos trabalho com desenvolvimento de Jogos utilizando Unity
Respeito as regras : NullReferenceException: Object reference not set to an instance WvDYdlf

https://gbxgamers.com

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