Referência nula em script da Unity
2 participantes
Página 1 de 1
Referência nula em script da Unity
Eu to fazendo um joguinho 2D onde meu player tem que atacar os inimigos que perseguem ele, dai eu fiz um collider para a espada que é ativada somente quando o player ataca, e esse colider ao contato com inimigo deveria causar dano e diminuir na barra de vida, mas ta dando erro de referencia nula, essa aqui:
NullReferenceException: Object reference not set to an instance of an object
PlayerAttack.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/PlayerAttack.cs:21)
E eu nao sei o que fazer, poderiam me ajudar?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBehaviour : MonoBehaviour
{
public enum State
{
PATROL,
CHASE
}
public State state;
private bool alive;
public Transform wayPointOne, wayPointTwo;
Vector3 localScale;
bool movingRight;
Rigidbody2D rb;
public float moveSpeed = 3f;
public float speed = 5;
public Animator anim;
public Transform Player;
public int maxHealth = 20;
public int currentHealth;
public HealthBar healthBar;
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
state = EnemyBehaviour.State.PATROL;
alive = true;
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
void Update()
{
StartCoroutine("FSM");
}
IEnumerator FSM()
{
while(alive)
{
switch(state)
{
case State.PATROL:
Patrol();
break;
case State.CHASE:
Chase();
break;
}
yield return null;
}
}
void Patrol()
{
anim.SetBool("isWalking", true);
if(transform.position.x > wayPointTwo.position.x)
movingRight = false;
if(transform.position.x < wayPointOne.position.x)
movingRight = true;
if(movingRight)
MoveRight();
else
MoveLeft();
}
void MoveRight()
{
movingRight = true;
localScale.x = 1.5f;
transform.localScale = localScale;
rb.velocity = new Vector2 (localScale.x * moveSpeed, rb.velocity.y);
}
void MoveLeft()
{
movingRight = false;
localScale.x = -1.5f;
transform.localScale = localScale;
rb.velocity = new Vector2 (localScale.x * moveSpeed, rb.velocity.y);
}
void Chase()
{
rb.velocity = new Vector2 (localScale.x * moveSpeed, rb.velocity.y);
if(transform.position.x < Player.position.x)
{
transform.localScale = new Vector3(1.5f, 1.5f , 1);
}
else
{
transform.localScale = new Vector3(-1.5f, 1.5f, 1);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.GetType() == typeof(BoxCollider2D))
{
if (other.gameObject.tag == "Player")
{
state = EnemyBehaviour.State.CHASE;
}
}
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
}
public void Damage()
{
healthBar.SetMaxHealth(maxHealth);
}
}
Esse é o codigo que ta dando a referencia nula, no inspetor ta tudo certinho
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
EnemyBehaviour enemyBehaviour;
public int playerAttack = 5;
void Start()
{
enemyBehaviour = GetComponent<EnemyBehaviour>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
enemyBehaviour.TakeDamage(playerAttack);
enemyBehaviour.Damage();
}
}
}
NullReferenceException: Object reference not set to an instance of an object
PlayerAttack.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/PlayerAttack.cs:21)
E eu nao sei o que fazer, poderiam me ajudar?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBehaviour : MonoBehaviour
{
public enum State
{
PATROL,
CHASE
}
public State state;
private bool alive;
public Transform wayPointOne, wayPointTwo;
Vector3 localScale;
bool movingRight;
Rigidbody2D rb;
public float moveSpeed = 3f;
public float speed = 5;
public Animator anim;
public Transform Player;
public int maxHealth = 20;
public int currentHealth;
public HealthBar healthBar;
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
state = EnemyBehaviour.State.PATROL;
alive = true;
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
void Update()
{
StartCoroutine("FSM");
}
IEnumerator FSM()
{
while(alive)
{
switch(state)
{
case State.PATROL:
Patrol();
break;
case State.CHASE:
Chase();
break;
}
yield return null;
}
}
void Patrol()
{
anim.SetBool("isWalking", true);
if(transform.position.x > wayPointTwo.position.x)
movingRight = false;
if(transform.position.x < wayPointOne.position.x)
movingRight = true;
if(movingRight)
MoveRight();
else
MoveLeft();
}
void MoveRight()
{
movingRight = true;
localScale.x = 1.5f;
transform.localScale = localScale;
rb.velocity = new Vector2 (localScale.x * moveSpeed, rb.velocity.y);
}
void MoveLeft()
{
movingRight = false;
localScale.x = -1.5f;
transform.localScale = localScale;
rb.velocity = new Vector2 (localScale.x * moveSpeed, rb.velocity.y);
}
void Chase()
{
rb.velocity = new Vector2 (localScale.x * moveSpeed, rb.velocity.y);
if(transform.position.x < Player.position.x)
{
transform.localScale = new Vector3(1.5f, 1.5f , 1);
}
else
{
transform.localScale = new Vector3(-1.5f, 1.5f, 1);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.GetType() == typeof(BoxCollider2D))
{
if (other.gameObject.tag == "Player")
{
state = EnemyBehaviour.State.CHASE;
}
}
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
}
public void Damage()
{
healthBar.SetMaxHealth(maxHealth);
}
}
Esse é o codigo que ta dando a referencia nula, no inspetor ta tudo certinho
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
EnemyBehaviour enemyBehaviour;
public int playerAttack = 5;
void Start()
{
enemyBehaviour = GetComponent<EnemyBehaviour>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
enemyBehaviour.TakeDamage(playerAttack);
enemyBehaviour.Damage();
}
}
}
AnaSenpai- Iniciante
- PONTOS : 2025
REPUTAÇÃO : 0
Respeito as regras :
Re: Referência nula em script da Unity
- Código:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
EnemyBehaviour enemyBehaviour;
public int playerAttack = 5;
void Start()
{
enemyBehaviour = GetComponent<EnemyBehaviour>(); //creio que seu erro esta aqui
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
enemyBehaviour.TakeDamage
enemyBehaviour.Damage();
}
}
não sei exatamente a sua ideia ,más suponho que,
GetComponent<EnemyBehaviour>(); // esta dando referencia ao proprio player no caso e nao ao inimigo; então o player ta tentando chamar o script que não esta nele (ele não tem) entao retorna nullo
gameobjetoInimigo.GetComponent<EnemyBehaviour>(); //aqui sim estaria dando referencia ao inimigo
entao quando o player entra no trigger do inimigo ele esta tentando chamar o script nele mesmo= "player" então dá uma referença nula
se seu jogo tem muitos inimigos voce pode armazenar todos os inimigos em um array de objeto com a mesma tag e chamar o script de todos eles como quiser
ex:
- Código:
public class PlayerAttack : MonoBehaviour
{
public GameObject[] enemies; //armazenar os inimigos
EnemyBehaviour[] enemyBehaviour; //armazenar o tipo do scripts dos inimigos
public int playerAttack = 5;
void Start()
{
enemies = GameObject.FindGameObjectsWithTag("Enemy"); //capturando todos os objetos inimigos e armazenando
//fazer o calculo dos inimigos armazenados
for (int quantidade=0; quantidade<enemies.Length; quantidade++)
{
enemyBehaviour =enemies[quantidade].GetComponents<EnemyBehaviour>(); //armazenando todos os EnemyBehavious dos inimigos
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
//calcular o total de comandos dos scripts e chamar o que quiser
for(int alvo=0; alvo< enemyBehaviour.Length; alvo++)
{
enemyBehaviour[alvo].TakeDamage(playerAttack);
enemyBehaviour[alvo].Damage();
}
}
}
}
ou
ex 2:
- Código:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
EnemyBehaviour enemyBehaviour; //armazenar um tipo de script ao entrar no trigger
public int playerAttack = 5;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
enemyBehaviour = other.gameObject.GetComponent<EnemyBehaviour>(); //captura o behaviour do inimigo
if(enemyBehaviour!=null)
enemyBehaviour.TakeDamage(playerAttack);
enemyBehaviour.Damage();
}
}
}
se tratando de triggers é um esquema mais ou menos assim,
espero que ajude em algo.
boa noite.
Re: Referência nula em script da Unity
Muito obrigada, funcionou :D
AnaSenpai- Iniciante
- PONTOS : 2025
REPUTAÇÃO : 0
Respeito as regras :
Tópicos semelhantes
» Script faz a função tudo certo na unity, já quando gero apk o script não faz a função
» [RESOLVIDO] Referência nula em variável Int
» [RESOLVIDO] Script/Unity
» SCRIPT TIRO - UNITY 3d
» Erro de script Unity 5
» [RESOLVIDO] Referência nula em variável Int
» [RESOLVIDO] Script/Unity
» SCRIPT TIRO - UNITY 3d
» Erro de script Unity 5
Página 1 de 1
Permissões neste sub-fórum
Não podes responder a tópicos