Spawn object sending var to object in hierarchy

Hey guys, im not too sure if this is a scripting problem.
I’ve been trying to get a mobs spawning into my rpg im making but ive come across a problem.
My monster spawn and my player is able to do damage to them, however my player doesn’t receive the exp from the monster when they die.
The exp still goes into the players prefab in my prefab folder in the game project though. So the monster are sending out the exp, its just not going to the player in the Hierarchy. If I stop the game and then restart the game my player then gets all the exp he was meant to get in the last play.

function Dead()
{
player.EXP += EXPgain;
Destroy(gameObject);
}

is the script im using to transfer the exp
ive tryed dragging my player from the Hierarchy into my monster prefab script for the player var but it will only let me put prefabs from the project folders.

It all works fine if I put the monster into the Hierarchy and then put the player into the script so maybe I should just hide the monsters somewhere in the map instead :stuck_out_tongue:

From what I understand you will need to get a reference to your player first. That can be achieved in some ways, the easiest would be to use FindObjectOfType in Start() to fill your reference variable. This will give you the first object found with the component of type attached to it. Ex:

private PlayerComponentScript player;

void Start()
{
    player = Object.FindObjectOfType(typeof(PlayerComponentScript));
}

Another way would be to first get your player gameObject by tag (make sure to set that!), then get the reference to the component:

private GameObject playerGameObject;
private PlayerComponentScript player;

void Start()
{
    playerGameObject = GameObject.FindWithTag("Player");
    if (playerGameObject != null)
    {
        player = playerGameObject.GetComponent<PlayerComponentScript>();
    }
}

Or, if you use your player component in many places, you may want to use a singleton:

public static PlayerComponentScript Instance;

void Awake()
{
    PlayerComponentScript.Instance = (PlayerComponentScript)this;
}

and then in your XP gain script you can do

void Dead()
{
    PlayerComponentScript.Instance.EXP += EXPgain;
    Destroy(gameObject);
}

(forgive me for using C# here)

Thank you for fast reply!
unfortunately i only know javascript so have, ive tryed converting it those scripts into java but havent had any luck yet.
At least I understand what I need do now though!
Thanks again! :smile: