Error when I left click:
“NullReferenceException: Object reference not set to an instance of an object
SwordManager.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Weapons/SwordManager.cs:26)”
(In the posted code the error line is 27)
In PlayerManager I set a bool, leftClick to true when I left click, then after 5 seconds I set it to false.
In SwordManager, I am trying to make it so when the sword collides with the enemy (onTrigger) AND the player has left clicked (leftCick is true), then the enemy takes damage.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwordManager : MonoBehaviour
{
private PlayerManager player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
GameObject objectCollided = other.gameObject;
if (other.gameObject.tag == "enemy")
{
//Debug.Log("Collision with sword!");
if (player.leftClick == true)
{
objectCollided.GetComponent<EnemyManager>().ChangeEnergy(-5);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
public class PlayerManager : MonoBehaviour
{
public static PlayerManager instance; //singleton
public GameObject player;
public PlayerMovementManager movementManager;
private EnemyManager enemy;
private SwordManager sword;
public Animator anim;
public bool leftClick = false;
//Health Variables
[SerializeField] private float currentEnergy;
[SerializeField] private float maxEnergy;
public Image EnergyBar;
//Cheats
private bool invincible = false;
private void Awake()
{
anim = GetComponent<Animator>();
// Has the singleton not been created yet
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
void Start()
{
movementManager = GetComponent<PlayerMovementManager>();
currentEnergy = 100f;
EnergyBar.fillAmount = 1;
}
void Update()
{
CheckInvincibility();
PerformAttack();
}
void FixedUpdate()
{
//Debug.Log("Able to attack: " + leftClick);
}
//Methods
void PerformAttack()
{
if (Input.GetMouseButton(0))
{
anim.SetInteger(HashIDs.slashCond_Int, 1);
leftClick = true;
Invoke("DisableAttack", 5f);
}
else
{
anim.SetInteger(HashIDs.slashCond_Int, 0);
}
}
void DisableAttack()
{
leftClick = false;
}
}