- Home /
Question by
unity_jS8_2lCoJ2YOEg · Feb 26 at 05:57 PM ·
scripting problemmovementplayerunity 2d
Fuel bar doesn't work!
So, I'm trying to make a fuel bar, but it isn't working completely.
I have an object in my scene and if I collide with it, I want it to fully set my fuel storage back to 100. But that is not working, and I don't know why.
PickUp script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPickUpManager : MonoBehaviour
{
private PlayerMovement playerMovement;
void Awake()
{
playerMovement = GameObject.FindObjectOfType<PlayerMovement>();
}
private void OnTriggerEnter2D(Collider2D coll)
{
if(coll.gameObject.CompareTag("Player"))
{
Destroy(gameObject);
playerMovement.AddFuel();
}
}
}
AddFuel Method
public void AddFuel()
{
slider.value = 100;
}
Comment
Answer by Caeser_21 · Feb 26 at 06:40 PM
This is happening because you are destroying the gameObject before you call the "AddFuel" function.
So, the "AddFuel" function won't get called...
To fix it just change it to
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPickUpManager : MonoBehaviour
{
private PlayerMovement playerMovement;
void Awake()
{
playerMovement = GameObject.FindObjectOfType<PlayerMovement>();
}
private void OnTriggerEnter2D(Collider2D coll)
{
if(coll.gameObject.CompareTag("Player"))
{
playerMovement.AddFuel()
Destroy(gameObject);
}
}
}
Ah, right! That's so stupid of me..
I also changed the "AddFuel" function from:
public void AddFuel()
{
slider.value = 100;
}
to:
public void AddFuel()
{
currentFuel = 100;
}
Thanks!