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:
Jogo multiplayer com steam
Mini Quarteirão com Texturas 3D VENDA
Controle do braço e cabeça no fps
PRECISO FAZER QUE MEU GAME FIQUE ONLINE
Como resolver vazamento de memoria?
Procuro Pessoas para Projeto
Ativar o objeto correto em Clones.
[TUTORIAL] Como fazer um interruptor simples (Unity 2018)
Unity-RawImages e Renderizção c/ Câmera Jogo Lento e travnado. Alguém pfv?!
Preciso de 20 testadores jogo mobile
O Labirinto II - Trailer Oficial
Ue posso divulgar meu game que ainda esta em criaçao aqui no forum?
[RESOLVIDO] Inverter o sprite para a direçao que o personagem anda.
Set Active não a reabiilitado C#
Build APK VR Google Cardbord com video.
[PROGRAMADOR FREELA] $$
Mais Um jogo!
Collider (mesh?)
[TUTORIAL] Deformar mesh com batidas (para objetos, veículos, etc)
WW2 Low poly Pack (Free)
Procuro freelancer
Novo Teaser do jogo Dark Age
Unity Admob Erro
DEATH ISLAND 0.2.5 SURVIVAL GAME 4 ANOS EM DESENVOLVIMENTO
Player travando na colisão com o chão Unity 2D
Sombras estão quadradas na build
nao consigo fazer o player sentar no sofa alguem me ajuda
Unity - Ao mudar de scene, todas as Lights são deletadas
210 Linhas de código para inimigo é muito grande?
modelar avatar e skins para um jogo web
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
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
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
Ontem à(s) 5:53 pm
Qui Jul 25, 2024 2:48 pm
Dom Jul 21, 2024 7:07 pm
Dom Jul 21, 2024 12:07 am
Seg Jul 15, 2024 7:02 pm
Dom Jul 14, 2024 11:24 pm
Sáb Jul 13, 2024 12:33 am
Qui Jun 27, 2024 5:49 pm
Sáb Jun 22, 2024 9:05 pm
Qui Jun 20, 2024 12:30 pm
Dom Jun 09, 2024 7:43 pm
Dom Jun 09, 2024 2:16 pm
Seg Jun 03, 2024 11:39 am
Seg maio 27, 2024 12:45 pm
Seg maio 20, 2024 9:01 pm
Dom maio 19, 2024 3:08 pm
Sáb maio 18, 2024 11:46 am
Sáb maio 11, 2024 8:55 am
Qui maio 09, 2024 11:33 pm
Seg Abr 29, 2024 9:34 pm
Qui Abr 25, 2024 3:34 pm
Seg Abr 22, 2024 5:15 pm
Seg Abr 15, 2024 12:23 pm
Qua Abr 10, 2024 1:33 am
Ter Abr 09, 2024 10:28 am
Seg Abr 08, 2024 9:27 pm
Seg Abr 08, 2024 8:01 am
Sáb Abr 06, 2024 8:05 pm
Qui Abr 04, 2024 11:34 pm
Qui Abr 04, 2024 11:13 pm
Sex Mar 22, 2024 2:41 pm
Dom Mar 10, 2024 2:30 pm
Sex Mar 01, 2024 1:27 pm
Qui Fev 22, 2024 9:57 pm
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 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



































































































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 : 541
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 : 2098
REPUTAÇÃO : 7
Idade : 37
Á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 : 541
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 : 541
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 : 1958
REPUTAÇÃO : 29
Idade : 24
Á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 : 541
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 : 2098
REPUTAÇÃO : 7
Idade : 37
Á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 : 541
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 : 977
REPUTAÇÃO : 5
Idade : 17
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 : 2098
REPUTAÇÃO : 7
Idade : 37
Á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 : 2098
REPUTAÇÃO : 7
Idade : 37
Á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