I am getting more and more frustrated and just can’t get to the bottom of this problem I have.I want to call a function from another Script in my “Player”-Script but Unity keeps throwing this error: NullReferenceException: Object reference not set to an instance of an object
Player.Start () (at Assets/Scripts/Player.cs:22)
I have looked up multiple solutions but none of them seem to work. What is confusing me, is the fact that the functions and the class itself in the “PowerBar”-Script show that they are being referenced in the “Player”-Script. I don’t get why Unity tells me that they are not referenced to.
This is the Player-Script: (PlayerMovement is the CharacterController-Script, which works perfectly fine)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public PlayerMovement playerMovement;
float horMove = 0f;
bool jump = false;
bool crouch = false;
public float runSpeed = 40f;
public PowerBar powerBar;
public int minPower = 10;
public int currentPower;
// Start is called before the first frame update
void Start()
{
currentPower = minPower;
powerBar.SetMinPower(minPower);
}
// Update is called once per frame
void Update()
{
PlayerInput();
GainPower(10);
}
void FixedUpdate()
{
// Move Character
playerMovement.Move(horMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
void PlayerInput()
{
horMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if(Input.GetButtonDown("Jump"))
{
jump = true;
}
if(Input.GetButtonDown("Crouch"))
{
crouch = true;
} else if(Input.GetButtonUp("Crouch"))
{
crouch = false;
}
}
void GainPower(int gain)
{
if(Input.GetKeyDown(KeyCode.Y))
{
currentPower += gain;
powerBar.SetPower(currentPower);
}
}
}
This is the PowerBar Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PowerBar : MonoBehaviour
{
public Slider slider;
public Gradient gradient;
public Image fill;
public void SetMinPower(int power)
{
slider.minValue = power;
slider.value = power;
fill.color = gradient.Evaluate(1f);
}
public void SetPower(int power)
{
slider.value = power;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
I hope someone can help me because I spent way too much time on this simple problem. Both of the Scripts are stored in the same folder by the way, so that can’t be the problem.