Hello, i started coding a few weeks ago and im are having this issue
‘NullReferenceException: Object reference not set to an instance of an object
Enemy.Update () (at Assets/Scripts/Enemy.cs:34)’. Im are following a youtube tutorial (portuguese brazilian) and I dont know how to fix this issue. The enemy was suposed to walk in the direction of the player but its stays still and dont move.
Youtube link:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float maxSpeed;
public float minHeight, maxHeight;
private float currentSpeed;
private Rigidbody rb;
private Animator anim;
private Transform groundCheck;
private bool onGround;
private bool facingRight = false;
private Transform target;
private bool isDead = false;
private float zForce;
private float walkTimer;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
groundCheck = transform.Find("GroundCheck");
target = FindObjectOfType<Player>().transform;
}
// Update is called once per frame
void Update()
{
onGround = Physics.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
anim.SetBool("Grounded", onGround);
facingRight = (target.position.x < transform.position.x) ? false : true;
if (facingRight)
{
transform.eulerAngles = new Vector3(0, 180, 0); // se esta virado para a direita, vira pra esquerda
}
else //vira pra direita
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
walkTimer += Time.deltaTime;
}
private void FixedUpdate()
{
if(!isDead)
{
Vector3 targetDistance = target.position - transform.position;
float hForce = targetDistance.x / Mathf.Abs(targetDistance.x); // h force é -1 se o player estiver na esquerda e +1 se na direita movimentaçao
if(walkTimer >= Random.Range(1f,2f))// entre 1 e 2 seg muda a movimentaçao
{
zForce = Random.Range(-1, 2);
walkTimer = 0;
}
if(Mathf.Abs(targetDistance.x) < 1.5f)
{
hForce = 0;
}
rb.velocity = new Vector3(hForce * currentSpeed, 0, zForce * currentSpeed);
anim.SetFloat("Speed", Mathf.Abs(currentSpeed));
}
rb.position = new Vector3 // trava o inimigo na camera
(
rb.position.x,
rb.position.y,
Mathf.Clamp(rb.position.z, minHeight, maxHeight));
}
void ResetSpeed()// reseta a velocidade/ idlee chama
{
currentSpeed = maxSpeed;
}
}