referencing another script in Unity

 a basic thing, I seem to always forget

two good threads on the topic:
https://forum.unity.com/threads/calling-function-from-other-scripts-c.57072/
https://forum.unity.com/threads/passing-a-game-object-reference-into-script.774251/

  • I have a script KarmaPlayer that has a function I want to call
    • changeKarma(int change)
this is a game pickup item that updates the karma value for the player
and then deactivates itself

//

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KarmaPickup : MonoBehaviour
{
    public int KarmaValue;

    KarmaPlayer karmaPlayer; //variable of type KarmaPlayer (the name of the script / class)


    void Start()
    {
        karmaPlayer = GameObject.Find("KarmaText(TMP)").GetComponent<KarmaPlayer>();
        //GameObject.Find("name of the game object").
        //finds the game object with the script / component
        //GetComponent<type>();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (karmaPlayer != null)
        {
            karmaPlayer.changeKarma(KarmaValue);
            this.gameObject.SetActive(false); //deactivate the pickup
        }
    }

}

Comments

Popular posts from this blog

guy

magenta girl

Culture today (work in progress)