I’m here again with my ghosts and an embarrassing problem with my game.
There are “evil” ghosts, but also some that act as a sort of spirit guide for the player, which we will call “Handmaids”, both follow the player.
To avoid the “null reference” error when one of the two ghosts spawned, I decided to divide the movement method into two parts and put one of them in if cicle: one that always follows the player, and the other where the ghosts follow the Handmaids (in the inherited class the opposite happens). When approaching a certain distance, the ghosts stop following the player to follow the Handmaids, but the condition within the method is ignored.
Thank You for your help.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.Timeline;
public class EnemyMovement : MonoBehaviour
{
Void Awake
{
spriteRenderer = GetComponentInChildren<SpriteRenderer>();
player = GameObject.FindGameObjectWithTag("Player");
targetPlayer = player.transform;
handMaid = GameObject.FindGameObjectWithTag("HandMaid");
}
public GhostsScriptable accessGhosts;
public HandMaidsScriptable accessHandMaidsScripts;
protected SpriteRenderer spriteRenderer;
protected GameObject player, handMaid;
protected Transform targetPlayer, targetHandMaid;
[SerializeField] public float moveSpeed = 1.0f;
void FixedUpdate()
{
if(accessHandMaidsScripts.IsLive == true)
{
moveTo(targetPlayer.position, targetHandMaid.position);
Debug.Log("The Ghost Follow the Handmaid");
}
moveToPlayer(targetPlayer.position);
}
public virtual void moveToPlayer(Vector2 playerPosition)
{
transform.position = Vector2.MoveTowards(transform.position, targetPlayer.position,
moveSpeed * Time.deltaTime);
spriteRenderer.flipX = playerPosition.x > transform.position.x;
}
public virtual void moveToEnemies(Vector2 playerPosition, Vector2 handmaidPosition)
{
float distanceBTWHandmaids = Vector2.Distance(transform.position, handmaidPosition);
float distanceBTWPlayer = Vector2.Distance(transform.position, playerPosition);
targetHandMaid = handMaid.transform;
if (distanceBTWHandmaids <= distanceBTWPlayer)
{
Debug.Log($@"Check if follow the Handmaid: {accessGhosts.IsLive}");
transform.position = Vector2.MoveTowards(transform.position, targetHandMaid.position,
moveSpeed * Time.deltaTime);
spriteRenderer.flipX = playerPosition.x > transform.position.x;
} else
//Maybe can i reuse moveToPlayer Method
Debug.Log($@"Check if follow the Player: {accessGhosts.IsLive}");
transform.position = Vector2.MoveTowards(transform.position, targetPlayer.position,
moveSpeed * Time.deltaTime);
// I know, I need a better solution in future for this:
spriteRenderer.flipX = playerPosition.x > transform.position.x;
}
}