Adding x amount of energy in another Class issue C#

Hi, after some time spending & searching I have to give up on this one.

On my player I have a c# script named EnergyDrain.cs
Which as the name implies drains the player energy over x amount of time.

When the player pickup’s an energy boost ( variable ) the player has to gain that amount.
So, coming from an actionscript background. I thought to simply add a function that absorbs the boost and thus adding the amount to the overal energy with a max limit. I might be thinking totally wrong here, hench the error, and my question here.

in the pickup collider script once the collider successfully found the player i toss my picked up energy towards the energyDrain script to add that amount.

With the current script i get the warning “An object reference is required to access non-static member”
I am quite stuck here as why searches doesn’t help me, only confuse me more :slight_smile:

Here is the relevant code:
pickupObjectsTrigger.cs

public class pickupObjectsTrigger : MonoBehaviour {
	
	
	public GameObject pickupObject; //The object we are picking up
	public string pickupObjectName;
	public GameObject inventoryObject; 
	public float energyPower = 10;


	void Start () 
	{
		if (pickupObject == null) 
		{
			Debug.LogWarning("No object set for pickup!");
		}	
	}

				
	void OnTriggerStay(Collider other) 
	{		

			if(other.CompareTag("Player"))
	    	{
			

			if(pickupObject != null && other.CompareTag("Player") && Input.GetButtonDown("Use"))
	    	{

				pickupObject.transform.parent = inventoryObject.transform;
				transform.collider.isTrigger = false;
				if (pickupObjectName == "energy"){
					EnergyController.ADD_ENERGY(energyAmount);
				} 
				//other pickups

	    	}												
	}	

}

EnergyController.cs

public class EnergyController : MonoBehaviour {

	public float energy = 100f;
	public float maxEnergy = 100f;

	public float drainspeed;

	void Update () {
		if(isOn == true){

			if(energy > maxEnergy){
				energy = maxEnergy;
			}

			if (energy <=0)
			{
				energy = 0;
			} else {
				energy -= drainspeed*Time.deltaTime;
			}
		}
	}

	public static void ADD_ENERGY(int amount){
		energy = Mathf.Clamp(energy+amount, 0, 100);
	}

}

Thank you for your insight.

There are two primary solutions. First you can make ‘energy’ static:

  public static float energy = 100f;

The use of statics this way (i.e. to create what is essentially a global function) can lead to problems with maintainable code.

The second solution is to make ‘ADD_ENERGEY()’ not static. Then you could access it this way:

 GameObject.Find("TheNameOfTheGameObjectThatHasTheEnergyControllerScript").GetComponent<EnergyController>().ADD_ENERGY(enertyAmount);

Other solutions include using SendMessage and Events and Delegates.